save array of uiimage that takes parameter data to userdefault in swift

To save an array of UIImage to UserDefaults, follow these steps:

  1. Convert the UIImage objects to Data using the UIImageJPEGRepresentation or UIImagePNGRepresentation functions. The chosen function should be used depending on whether to prioritize image quality or file size. These functions return Data objects that can be saved to UserDefaults.

  2. Save the Data objects to an array.

  3. Save the array to UserDefaults using the setObject function. Make sure to use the synchronize function to ensure the saved data is written to disk.

Here's the example code:

main.swift
// Images array
var images = [UIImage]()

// Data objects array
var imageDataArray = [Data]()

// Add UIImage objects to the images array
images.append(UIImage(named: "image1")!)
images.append(UIImage(named: "image2")!)
images.append(UIImage(named: "image3")!)

// Convert UIImage objects to Data objects and add to the imageDataArray array
for image in images {
   let imageData = UIImageJPEGRepresentation(image, 1)
   imageDataArray.append(imageData!)
}

// Save the imageDataArray to UserDefaults
UserDefaults.standard.set(imageDataArray, forKey: "savedImages")
UserDefaults.standard.synchronize()
602 chars
21 lines

To retrieve the saved images array from UserDefaults at a later date:

main.swift
if let imageDataArray = UserDefaults.standard.array(forKey: "savedImages") as? [Data] {
    // Convert Data objects back to UIImage objects
    for imageData in imageDataArray {
        let image = UIImage(data: imageData)
        images.append(image!)
    }
}
261 chars
8 lines

gistlibby LogSnag