save array uiimage to user defaults in swift

To save an array of UIImage objects to UserDefaults, they need to be converted to Data objects first. Here's an example of how to save an array of images:

main.swift
// Define an array of images
let images = [UIImage(named: "image1")!, UIImage(named: "image2")!]

// Convert the array of images to an array of Data
let imageData = images.map { $0.pngData() }

// Save the array of Data to UserDefaults
UserDefaults.standard.set(imageData, forKey: "savedImages")
296 chars
9 lines

In this example, we first define an array of UIImage objects. We then use the map function to convert the array of images to an array of Data, where each image is converted to its PNG data representation. Finally, we save the array of Data to UserDefaults using the key "savedImages".

To retrieve the array of images from UserDefaults:

main.swift
// Retrieve the array of Data from UserDefaults
let imageData = UserDefaults.standard.array(forKey: "savedImages") as? [Data]

// Convert the array of Data back to an array of UIImage
let images = imageData?.map { UIImage(data: $0)! }
235 chars
6 lines

This code retrieves the array of Data from UserDefaults using the key "savedImages". We then use the map function again to convert the array of Data back to an array of UIImage objects.

gistlibby LogSnag