Reputation: 3680
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?
}
}
Upvotes: 1
Views: 3587
Reputation: 1325
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)
}
}
}
}
Upvotes: 2