0

Hi i have a imageview and a button underneath which is called upload. When the user clicks on the button upload they can access there gallery and choose an image to set to the image view. When i close the app the image that has been set keeps disappearing. I was wondering i would have to use user defaults to save the image locally but i am not sure how to do this. I have provided my code down below.

image

var image:UIImageView = {
    let image = UIImageView()
    image.translatesAutoresizingMaskIntoConstraints = false
    image.backgroundColor = .black
    return image
}()

image picker controller

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    if let uploadedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
    {
 
        image.image = uploadedImage
        
        
        
    }else{
        
    }
    self.dismiss(animated: true, completion: nil)
}   
BigZ
  • 19
  • 3
  • Take a look at this, https://stackoverflow.com/questions/43016666/how-to-save-a-uiimage-to-documents-directory. Then you can save that directory URL to user defaults and access whenever. – Harry J Aug 09 '20 at 03:15

1 Answers1

1

You can save any UIImage as data like:

UserDefaults.standard.setValue(uploadedImage.pngData()!, forKey: "uploadedImage")

And load like:

let loadedImage = UIImage(data: UserDefaults.standard.data(forKey: "uploadedImage")!)

But I highly recommend you to not save this image in the user defaults. Instead, use a file in the Documents directory

Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278
  • Thanks i might use core data to save the image – BigZ Aug 08 '20 at 17:54
  • Just save your image to your application support directory. If your want the user to be able to access the image you can save it in the documents directory – Leo Dabus Aug 08 '20 at 18:00