save uiimage to user defaults in swift

To save a UIImage to user defaults in Swift, we need to convert the UIImage to Data using UIImagePNGRepresentation or UIImageJPEGRepresentation method and then save the Data to user defaults.

It is also possible to achieve this using the Codable protocol or archiving approach which allows for storing complex objects like UIImage into user defaults.

Here is the sample code using UIImagePNGRepresentation method:

main.swift
// Get UIImage object
guard let image = UIImage(named: "myImage") else { return }

// Convert UIImage to Data
guard let imageData = UIImagePNGRepresentation(image) else { return }

// Save image data to user defaults
UserDefaults.standard.set(imageData, forKey: "myImageKey")
276 chars
9 lines

And here is the sample code using Codable approach:

main.swift
// Get UIImage object
guard let image = UIImage(named: "myImage") else { return }

// Encode UIImage to Data using Codable
let encoder = JSONEncoder()
guard let imageData = try? encoder.encode(image) else { return }

// Save image data to user defaults
UserDefaults.standard.set(imageData, forKey: "myImageKey")
312 chars
10 lines

And finally, here is the sample code using archiving approach:

main.swift
// Get UIImage object
guard let image = UIImage(named: "myImage") else { return }

// Archive UIImage to Data
let imageData = NSKeyedArchiver.archivedData(withRootObject: image)

// Save image data to user defaults
UserDefaults.standard.set(imageData, forKey: "myImageKey")
274 chars
9 lines

gistlibby LogSnag