save array uiimage that has a type data to user default in swift

To save an array of UIImages to User Defaults, you need to convert the array to an array of Data objects, which can be stored in User Defaults. Here is the code to do that:

main.swift
// First, convert the array of UIImages to an array of Data objects
let imageDataArray = imageArray.map { image in
    return image.pngData()
}

// Then, save the array of Data objects to User Defaults
UserDefaults.standard.set(imageDataArray, forKey: "myImageArray")
268 chars
8 lines

To retrieve the array of UIImages from User Defaults, you need to reverse the process:

main.swift
// First, get the array of Data objects from User Defaults
guard let imageDataArray = UserDefaults.standard.array(forKey: "myImageArray") as? [Data] else {
    return // handle error: the array does not exist or is not of the correct type
}

// Then, convert the array of Data objects to an array of UIImages
let imageArray = imageDataArray.compactMap { data in
    return UIImage(data: data)
}
395 chars
10 lines

Note that if the array of UIImages is large, it may be more efficient to save it to disk instead of User Defaults. In that case, you can use FileManager to write the array of Data objects to a file, and read it back when needed.

gistlibby LogSnag