Ios Swift 3.0:如何保存用户&x27;从imagePicker获取应用程序中的图像

Ios Swift 3.0:如何保存用户&x27;从imagePicker获取应用程序中的图像,ios,swift3,uiimageview,xcode8,uiimagepickercontroller,Ios,Swift3,Uiimageview,Xcode8,Uiimagepickercontroller,我正在尝试让用户从他们的图库或相机中选择一幅图像,然后将其上传到应用程序。这是可行的,但唯一的问题是它不会将其保存在应用程序中。一旦用户关闭应用程序,用户选择的图像就会消失。我也没有任何保存功能,因为我不知道如何实现它 我正在Swift 3.0中使用Xcode 8.3.2。代码如下: import UIKit class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationCont

我正在尝试让用户从他们的图库或相机中选择一幅图像,然后将其上传到应用程序。这是可行的,但唯一的问题是它不会将其保存在应用程序中。一旦用户关闭应用程序,用户选择的图像就会消失。我也没有任何保存功能,因为我不知道如何实现它

我正在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)
}
在您看来,load是否使用了检索方法
如果图像存在且为nsdata格式,则只有它将显示保存图像。就是这样。

记住要保存图像,您需要将图像存储为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)
}
在您看来,load是否使用了检索方法
如果图像存在且为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
    }
}

您可以使用您喜欢的任何名称并使用不同的名称存储图像以存储多个图像。

您可以使用以下功能将图像保存到文档目录中

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


您可以使用任何喜欢的名称并使用不同的名称存储图像以存储多个图像。

如果您不使用任何数据库,则只需使用nsusedefault在设备上本地保存图像或任何数据即可。如果您不使用任何数据库,则只需使用nsusedefault在设备上本地保存图像或任何数据即可。和使用getter/setter检索appVariable中的任意位置不能有初始值:预期的声明使用未解析标识符“intFileRef”使用未解析标识符“defaults”计算属性必须有显式类型Insert“:“let”声明不能计算属性行上的连续声明必须是以“;”分隔插入“;”使用未解析标识符“println”使用未解析标识符“defaults”使用未解析标识符“intFileRef”好的,将发布swift 3的新语法这是正确的代码。我编辑了我的asnwer,应该可以使用。在需要的地方使用save方法,并在需要显示图像的地方调用方法。希望有帮助:)请检查我的答案。我添加了很多评论,现在应该可以工作了,谢谢。我只是不知道该把代码放在哪里。我是否将其放在viewDidLoad()中?具有getter/setter的变量不能有初始值:未解析标识符“intFileRef”的预期声明使用未解析标识符“defaults”计算属性必须有显式类型Insert“:“let”声明不能计算属性行上的连续声明必须用“;”分隔插入“;”使用未解析标识符“println”使用未解析标识符“defaults”使用未解析标识符“intFileRef”好的,将发布swift 3的新语法这是正确的代码。我编辑了我的asnwer,应该可以使用。在需要的地方使用save方法,并在需要显示图像的地方调用方法。希望有帮助:)请检查我的答案。我添加了很多评论,现在应该可以工作了,谢谢。我只是不知道该把代码放在哪里。我是否将其放在viewDidLoad()中?我添加了这两个函数,但当我关闭应用程序并重新打开它时,用户上载的图像仍然会消失。您将从getImage()函数获取url,您需要从中获取图像。我如何更改url路径以匹配imagePicker中用户的图像?ImagePickerController IDCancel???当用户点击“取消”按钮时,它将被调用您需要在didFinishPickingMediaWithInfoI中调用saveImageDocumentDirectory(),我添加了这两个函数,但当我关闭应用程序并重新打开它时,用户上传的图像仍然消失。您将从getImage()函数中获取url,您需要从i获取图像我如何更改url路径以匹配来自imagePicker的用户图像?ImagePickerController IDCancel???当用户点击“取消”按钮时,它将被调用。您需要在didFinishPickingMediaWithInfo中调用saveImageDocumentDirectory()