save a uiimage that takes parameter data to userdafult in swift

To save a UIImage in UserDefaults you need to convert it into data using UIImageJPEGRepresentation or UIImagePNGRepresentation function.

Here is a sample code to save a UIImage in UserDefaults:

main.swift
// Assume image is the UIImage that you want to save in UserDefaults
let imageData = UIImageJPEGRepresentation(image, 1.0) // or UIImagePNGRepresentation(image)
UserDefaults.standard.set(imageData, forKey: "savedImage")
220 chars
4 lines

The UIImageJPEGRepresentation function will convert the UIImage into a JPEG format, with quality of 1.0 being the maximum. You can also use the UIImagePNGRepresentation function to convert the UIImage into a PNG format.

Note that saving large amounts of data in UserDefaults is not recommended. For saving large images, it is better to store them in the file system and save the file URL in UserDefaults.

gistlibby LogSnag