Swift 3.0:如何通过 imagePicker 在应用程序中保存用户图像
Swift 3.0: How to save a user's image in the app from an imagePicker
我正在尝试让用户从他们的画廊或相机中选择一张图片,然后将其上传到应用程序。这可行,但唯一的问题是它不会将其保存在应用程序中。一旦用户关闭应用程序,用户选择的图像就会消失。我也没有任何保存功能,因为我不知道如何实现。
我在 Swift 3.0 中使用 Xcode 8.3.2。这是下面的代码:
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func chooseImage(_ sender: Any) {
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
let actionSheet = UIAlertController(title: "Photo Source", message: "Choose a source", preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (action:UIAlertAction) in
if UIImagePickerController.isSourceTypeAvailable(.camera) {
imagePickerController.sourceType = .camera
self.present(imagePickerController, animated: true, completion: nil)
}else{
print("Camera not available")
}
}))
actionSheet.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: { (action:UIAlertAction) in
imagePickerController.sourceType = .photoLibrary
self.present(imagePickerController, animated: true, completion: nil)
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(actionSheet, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
imageView.image = image
picker.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
记得保存图片你需要将图片存储为NSData
// Code to store image
let defaults = UserDefaults.standard
// To save as data:
// From StoryBoard, if you want to save "image" data on the imageView of
// MainStoryBoard, following codes will work.
let image = UIImagePNGRepresentation(imageView.image!) as NSData?
defaults.set(image, forKey: "test") // saving image into userdefault
// for retrieving the image
if (UserDefaults.standard.object(forKey: "test") as? NSData) != nil {
let photo = UserDefaults.standard.object(forKey: "test") as! NSData
img2.image = UIImage(data: photo as Data) // img2 set your imageview on which you want photo to appear
// Now you can set img2.image
}
已编辑
如何在你的代码中使用
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : Any]) {
let defaults = UserDefaults.standard
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
imageView.image = image
let saveImage = UIImagePNGRepresentation(image!) as NSData?
defaults.set(saveImage, forKey: "test") // saving image into userdefault
picker.dismiss(animated: true, completion: nil)
}
并且在您看来确实加载使用了检索方法
如果图像存在且为 nsdata 格式,则只有它会显示保存图像。就是这样。
您可以使用以下功能将图像保存在您的文档目录中
func saveImageDocumentDirectory(tempImage:UIImage){
let documentsDirectoryURL = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileURL = documentsDirectoryURL.appendingPathComponent("ImageName.png")
do {
try UIImagePNGRepresentation(tempImage)?.write(to: fileURL)
} catch {
print(error)
}
}
要检索图像,您可以使用
func getImage()->URL?{
let documentsDirectoryURL = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileURL = documentsDirectoryURL.appendingPathComponent("ImageName.png")
if FileManager.default.fileExists(atPath: fileURL.path){
return fileURL
}else{
return nil
}
}
您可以使用任何您喜欢的名称,并使用不同的名称存储图像以存储多个图像。
我正在尝试让用户从他们的画廊或相机中选择一张图片,然后将其上传到应用程序。这可行,但唯一的问题是它不会将其保存在应用程序中。一旦用户关闭应用程序,用户选择的图像就会消失。我也没有任何保存功能,因为我不知道如何实现。
我在 Swift 3.0 中使用 Xcode 8.3.2。这是下面的代码:
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func chooseImage(_ sender: Any) {
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
let actionSheet = UIAlertController(title: "Photo Source", message: "Choose a source", preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (action:UIAlertAction) in
if UIImagePickerController.isSourceTypeAvailable(.camera) {
imagePickerController.sourceType = .camera
self.present(imagePickerController, animated: true, completion: nil)
}else{
print("Camera not available")
}
}))
actionSheet.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: { (action:UIAlertAction) in
imagePickerController.sourceType = .photoLibrary
self.present(imagePickerController, animated: true, completion: nil)
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(actionSheet, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
imageView.image = image
picker.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
记得保存图片你需要将图片存储为NSData
// Code to store image
let defaults = UserDefaults.standard
// To save as data:
// From StoryBoard, if you want to save "image" data on the imageView of
// MainStoryBoard, following codes will work.
let image = UIImagePNGRepresentation(imageView.image!) as NSData?
defaults.set(image, forKey: "test") // saving image into userdefault
// for retrieving the image
if (UserDefaults.standard.object(forKey: "test") as? NSData) != nil {
let photo = UserDefaults.standard.object(forKey: "test") as! NSData
img2.image = UIImage(data: photo as Data) // img2 set your imageview on which you want photo to appear
// Now you can set img2.image
}
已编辑
如何在你的代码中使用
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : Any]) {
let defaults = UserDefaults.standard
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
imageView.image = image
let saveImage = UIImagePNGRepresentation(image!) as NSData?
defaults.set(saveImage, forKey: "test") // saving image into userdefault
picker.dismiss(animated: true, completion: nil)
}
并且在您看来确实加载使用了检索方法 如果图像存在且为 nsdata 格式,则只有它会显示保存图像。就是这样。
您可以使用以下功能将图像保存在您的文档目录中
func saveImageDocumentDirectory(tempImage:UIImage){
let documentsDirectoryURL = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileURL = documentsDirectoryURL.appendingPathComponent("ImageName.png")
do {
try UIImagePNGRepresentation(tempImage)?.write(to: fileURL)
} catch {
print(error)
}
}
要检索图像,您可以使用
func getImage()->URL?{
let documentsDirectoryURL = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileURL = documentsDirectoryURL.appendingPathComponent("ImageName.png")
if FileManager.default.fileExists(atPath: fileURL.path){
return fileURL
}else{
return nil
}
}
您可以使用任何您喜欢的名称,并使用不同的名称存储图像以存储多个图像。