Reputation: 75
I am trying to have a user choose an image from their gallery or camera, then upload it to the app. This works, but the only problem is that it doesn't save it in the app. As soon as the user closes the app, the image that the user chose disappears. I also do not have any save function because i don't know how to implement one.
I am using Xcode 8.3.2 in Swift 3.0. Here is the code below:
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.
}
@IBAction func chooseImage(_ sender: Any) {
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
let actionSheet = UIAlertController(title: "Photo Source", message: "Choose a source", preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (action:UIAlertAction) in
if UIImagePickerController.isSourceTypeAvailable(.camera) {
imagePickerController.sourceType = .camera
self.present(imagePickerController, animated: true, completion: nil)
}else{
print("Camera not available")
}
}))
actionSheet.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: { (action:UIAlertAction) in
imagePickerController.sourceType = .photoLibrary
self.present(imagePickerController, animated: true, completion: nil)
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(actionSheet, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
imageView.image = image
picker.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Upvotes: 0
Views: 1632
Reputation: 3367
Remember to save image you need to store image as NSData
// Code to store image
let defaults = UserDefaults.standard
// To save as data:
// From StoryBoard, if you want to save "image" data on the imageView of
// MainStoryBoard, following codes will work.
let image = UIImagePNGRepresentation(imageView.image!) as NSData?
defaults.set(image, forKey: "test") // saving image into userdefault
// for retrieving the image
if (UserDefaults.standard.object(forKey: "test") as? NSData) != nil {
let photo = UserDefaults.standard.object(forKey: "test") as! NSData
img2.image = UIImage(data: photo as Data) // img2 set your imageview on which you want photo to appear
// Now you can set img2.image
}
Edited
How to use in your code
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : Any]) {
let defaults = UserDefaults.standard
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
imageView.image = image
let saveImage = UIImagePNGRepresentation(image!) as NSData?
defaults.set(saveImage, forKey: "test") // saving image into userdefault
picker.dismiss(animated: true, completion: nil)
}
And in your view did load use retrieving method If the image exist and in nsdata format then only it will show save image. Thats it.
Upvotes: 2
Reputation: 3008
You can save image in your document directory with below function
func saveImageDocumentDirectory(tempImage:UIImage){
let documentsDirectoryURL = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileURL = documentsDirectoryURL.appendingPathComponent("ImageName.png")
do {
try UIImagePNGRepresentation(tempImage)?.write(to: fileURL)
} catch {
print(error)
}
}
To retrieve Image you can use
func getImage()->URL?{
let documentsDirectoryURL = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileURL = documentsDirectoryURL.appendingPathComponent("ImageName.png")
if FileManager.default.fileExists(atPath: fileURL.path){
return fileURL
}else{
return nil
}
}
You can use any name you like and store image with different name to store multiple image.
Upvotes: 0