Search code examples
uiimageviewsavexcode8uiimagepickercontroller

Saving UIImageView Locally


Right now I am able to have the user successfully take a picture using the camera and have their picture be uploaded into a imageview. However, if the user leaves that view controller when they eventually return the photo is no longer in that imageview. Is there anyway I am able to save the photo so that once a picture is taken and put into that imageview it is there until the user takes a different picture to replace it?

import UIKit

class ArsenalViewController: UIViewController, 
UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet var ball1: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
}
 override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}
 @IBAction func addPhoto1(_ sender: Any) {
    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera){
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.camera
        imagePicker.allowsEditing = false
        self.present(imagePicker, animated: true, completion: nil)
    }
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        ball1.contentMode = .scaleToFill
        ball1.image = pickedImage
    }
    picker.dismiss(animated: true, completion: nil)
}

Solution

  • First you need to save the image data somewhere (i.e. UserDefaults, Core Data, a database) and then retrieve it. UserDefaults is easy, try this:

        //Encoding
        let imageData:NSData = UIImageJPEGRepresentation(pickedImage!)! as NSData
    
        //Saved image
        UserDefaults.standard.set(imageData, forKey: "savedImage")
    
        //Decode
        if let data = UserDefaults.standard.object(forKey: "savedImage") as! NSData{
            myImageView.image = UIImage(data: data as Data)
        }
    

    Encoding and saving image should happen right after updating your image and decoding should be done once the view has loaded all of its elements (viewDidAppear method).

    After encoding and saving the image once, you can decode it anytime, even if the user left the VC and came back.