I'm building an app where I let the user to pick an image from its photo library. I was using this code to save it.
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
imgPicker.dismissViewControllerAnimated(true, completion: nil)
NSUserDefaults.standardUserDefaults().setValue(image, forKey: "bgImage")
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
imgPicker.dismissViewControllerAnimated(true, completion: nil)
}
I later figured out that you can't save the image with NSUserDefaults, but you can save the picked image's path, save it and load it with "if let..."
But I don't know how to do this (find the path and save it). The idea is for the user to choose the view background image, kinda like how Whatsapp does.
If I'm wrong and you can't store the path, is there any easy way to save the picked image without using online servers?
You can save and retrieve it using NSUserDefaults:
//Save image
let img = UIImage() //Change to be from UIPicker
let data = UIImagePNGRepresentation(img)
NSUserDefaults.standardUserDefaults().setObject(data, forKey: "myImageKey")
NSUserDefaults.standardUserDefaults().synchronize()
//Get image
if let imgData = NSUserDefaults.standardUserDefaults().objectForKey("myImageKey") as? NSData {
let retrievedImg = UIImage(data: imgData)
}
Or you can read / write to file, if you prefer:
//Save image
let img = UIImage() //Change to be from UIPicker
let data = UIImagePNGRepresentation(img)!
do {
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
try data.writeToFile("\(documentsPath)myImage", options: [])
} catch {
print("Error")
}
//Get image
do {
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let readData = try NSData(contentsOfFile: "\(documentsPath)myImage", options: [])
let retreivedImage = UIImage(data: readData)
}
catch {
print("Error")
}
Swift 3:
//Save image
let data = UIImagePNGRepresentation(pickedImage)!
do {
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
try data.write(to: URL(string: "\(documentsPath)/myImage")!, options: .atomic)
} catch {
print("Error")
}
//Get image
do {
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let readData = try Data(contentsOf: URL(string: "\(documentsPath)/myImage")!)
let retreivedImage = UIImage(data: readData)
} catch {
print("Error")
}