Paul Heinemeyer Paul Heinemeyer - 1 year ago 96
iOS Question

How to save an array of UIimages in xCode (swift)

I have an array of

, which is dynamic.
So the user can add photos to this array.
My question is how can I save this array, because I tried some things and none of them seem to work for me.
I would welcome suggestions how to accomplish this task.

Thank you.

Answer Source

If you want to use Core Data, I think the simplest way to save an array of images is to save them when a new image is added or an image is removed.

The Core Data data model is very simple. You can just add an entity called Image or whatever makes sense in your context. Add an image property to the entity. Set the property's type to "Data". Generate the NSManagedObject subclasses and the model is done.

Now, how and when do you need to save the images? I think you should insert an image to the Core Data context only when the user creates a new image. And you should remove an object from the Core Data context when the user removes an image. Because if the user does nothing the images in a session of your app, it's not necessary to save the images again.

To save a new image,

// I assume you have already stored the new image that the user added in a UIImage variable named imageThatTheUserAdded
let context = ... // get the core data context here
let entity = NSEntityDescription.entityForName(...) // I think you can do this yourself
let newImage = Image(entity: entity, insertIntoManagedObjectContext: context)
newImage.image = UIImageJPEGRepresentation(imageThatTheUserAdded, 1)
do {
} catch let error as NSError {

And I think you know how to remove an image from Core Data, right?

When the VC that needs to display the images is presented, you execute an NSFetchRequest and fetch all the images saved as [AnyObject] and cast each element to Image. Then, use the init(data:) initializer to turn the data to UIImages.


Here I'll show you how to get the images back as [UIImage]:

let entity = NSEntityDescription.entityForName("Image", inManagedObjectContext: dataContext)
let request = NSFetchRequest()
request.entity = entity
let fetched = try? dataContext.executeFetchRequest(request)
if fetched != nil {
    let images = fetched!.map { UIImage(data: ($0 as! Image).image) }
    // now "images" is the array of UIImage. use it wisely.