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

时间:2017-08-14 13:22:55

标签: ios swift3 uiimageview xcode8 uiimagepickercontroller

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

我在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.
    }


}

2 个答案:

答案 0 :(得分:1)

请记住保存将图像存储为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格式,则只显示保存图像。多数民众赞成。

答案 1 :(得分:0)

您可以使用以下功能

将图像保存在文档目录中
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
    }
}

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