Saving Images in CoreData
Is it possible to store UIImage in core data?

Yes, we can store the images with the core data but not directly as UIImage. This can be achieved by converting UIImage to Data. Because UIImage is not a valid attribute type in Core Data.

If you are new to the core data and want to learn from the basics then refer to this post. Hereby gonna discuss only saving images into core data.

The attribute type used to store image in the core data is Binary Data. So declare the attribute type as Binary Data in your model.

To convert an image into a portable data format like png or jpeg, use the below code:

2. Save the image in core data

3. To fetch the saved image from the core data, use the following code

4. Convert the imageData to UIImage to display it to the user

I am sure that every one of you might have achieved this process successfully. But few may fail, the reason is they will be storing an array of images in the core data.

So you may ask me, is it possible to store my array of images in the core data?. I would say yes, definitely you can and the steps to be followed for that also will be the same as the above one. OOPS!! not exactly the same one, few more secrets to be added to make it work.

For Example, consider this array of images

let myImages = [“car”, “pen”, “camera”, “bag”]

To store this array of images to core data, first convert each image into data and store it in an array.

2. Save array of images to core data

3. Fetch array of images from core data

4. Convert the array of imageData to UIImage as

NSKeyedArchiver is a class that serializes (converts) data very similar to JSONEncoder. NSKeyedUnArchiver is a class that de-serializes (re-converts) data back, very similar to JSONDecoder.

These two play a major role in storing an array of any type of data in the core data.

Tips: There is a way to see your stored images, just use the below code in your console.

po NSSearchPathForDirectoriesInDomains(. documentDirectory , .userDomainMask, true)

This will lead you to the destination of the SQLite file of your core data model. Using the tool DBBrowser for Sqlite you can see your stored images and other data. The tool which I mentioned is an example, there are huge number of tools available in the internet. You can use which you feel comfortable.

It’s interesting right, try this out guys and reach me on Twitter for any doubts and suggestions.
['Sridharan T']
['Swift Programming', 'Uiimage', 'iOS', 'Core Data', 'Swift']