1

In the app that i am making, the user will select a photo, then it will appear in the imageview. How do i save the image that they selected in the image.xcassets folder, so when i relaunch the app, the image will still be there?

Here is the code that i am using...

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

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func Action(sender: AnyObject) {

        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) {

            let imagePicker:UIImagePickerController = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
            imagePicker.allowsEditing = false

            self.presentViewController(imagePicker, animated: true, completion: nil)




        }

    }






    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {




           self.dismissViewControllerAnimated(true, completion: nil)

            self.imageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage

//how do i save the image in the folder?
        }





    }
nachshon f
  • 3,540
  • 7
  • 35
  • 67
  • One possible solution would be to create a CoreData object and save the image there as a base64 encoded string. That way the next time you open the app you can fetch the image from CoreData and display it upon relaunch. See http://stackoverflow.com/a/11251478/1457357 for an great explanation on encoding and decoding using base64. – c_rath Apr 01 '15 at 15:00

1 Answers1

2

You can do so by doing this

var finalImage : UIImage()

//Your Method
func saveImage () {

       self.imageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
       self.finalImage = self.imageView.image as UIImage

       let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
       let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
       if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) {

       if paths.count > 0 {
         if let dirPath = paths[0] as? String {
         let readPath = dirPath.stringByAppendingPathComponent("Image.png")
         let image = UIImage(named: readPath)
         let writePath = dirPath.stringByAppendingPathComponent("Image2.png") 
         UIImagePNGRepresentation(self.finalImage).writeToFile(writePath, atomically: true)
    } 
  }
 }


}
Jesse Onolemen
  • 1,277
  • 1
  • 15
  • 32