I_like_cocoa I_like_cocoa - 5 months ago 11
iOS Question

Saving ImageView content in memory? What is the best approach?

I've been looking for this answer online all morning long and I didn't find exactly what I needed. I want the user to add an image from his library and it would appear on the screen. I've managed to write the code that allows me to do that. However, I want that image to be saved. By that, I mean that I want the image selected to still appear after the user closes the app and reopens it. How can I do that?
Any help would be really appreciated :)
I've attached my code:

import UIKit

class Schedule: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet var imageView: UIImageView!
let imagePicker = UIImagePickerController()
@IBAction func addImage(sender: AnyObject) {

imagePicker.allowsEditing = false
// Only allow photos to be picked, not taken.
imagePicker.sourceType = .PhotoLibrary
presentViewController(imagePicker, animated: true, completion: nil)
}


// User picks image

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
imageView.contentMode = .ScaleAspectFit
imageView.image = pickedImage
}
dismissViewControllerAnimated(true, completion: nil)
}

// User cancels picking image action

func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}

override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self
}
}

Answer

You can do this using NSUserDefault, It will store your image data and you can retrieve it later. Change your viewDidLoad like this

override func viewDidLoad() {
super.viewDidLoad()        
     imagePicker.delegate = self 
     if let imageData = NSUserDefaults.standardUserDefaults().objectForKey("image") as? NSData {
         self.imageView.image = UIImage(data: imageData)
     }
}  

Now you need to store this imageData in NSUserDefault when you select image from UIImagePicker

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
         imageView.contentMode = .ScaleAspectFit
         imageView.image = pickedImage
         let data = UIImagePNGRepresentation(pickedImage)              
         NSUserDefaults.standardUserDefaults().setObject(data, forKey: "image")
         NSUserDefaults.standardUserDefaults().synchronize() 
     }        
     dismissViewControllerAnimated(true, completion: nil)                
}

Hope this will help you.