Swift 3.0:如何从应用程序保存用户的图像ImagePicker

问题描述:

我想让用户从他们的画廊或相机中选择一个图像,然后将其上传到应用程序。这有效,但唯一的问题是它不会将它保存在应用程序中。只要用户关闭应用程序,用户选择的图像就会消失。我也没有任何保存功能,因为我不知道如何实现它。Swift 3.0:如何从应用程序保存用户的图像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. 
    } 


} 
+0

如果您没有使用任何数据库,那么只需使用nsusedefault在设备上本地保存图像或任何数据。并检索应用程序中的任何地方 – cole

记得保存图像,你需要存储的图像作为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 forma那么只有它会显示保存图像。而已。

+0

这给了我很多错误。 – Vinny

+0

什么样的错误,你可以在这里发表。 – cole

+0

可变吸气剂/调节器不能具有一个初始值: 预期声明 使用未解决的识别符的“intFileRef” 使用未解决的识别符的“缺省” 计算属性必须具有显式类型 插入“:” '让我们声明无法计算属性 行上的连续声明必须用';'分隔 插入';' 使用的未解决的标识符“的println” 使用未解决的标识符“默认” \t使用未解决的标识符“intFileRef” – Vinny

你可以在你的文档目录中保存以下功能图像

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 
    } 
} 

你可以用你喜欢的任何名称和店铺形象与不同的名称来存储多个图像。

+0

我添加了这两个功能,但用户上传的图像仍然消失时,我关闭了应用程序,并重新打开它。 – Vinny

+0

是什么函数抛出错误? –

+0

你会从getImage()函数中获取url,你需要从中获取图像 –