BigZ
BigZ

Reputation: 19

How to save image in user defaults programmatically

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

Upvotes: 0

Views: 695

Answers (1)

Mojtaba Hosseini
Mojtaba Hosseini

Reputation: 119128

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

Upvotes: 1

Related Questions