Saving Images to Core Data in iOS

Enabling a user to be able to save and retrieve images within an app is a common app requirement which can enrich the user experience. Following is a basic tutorial for accomplishing this task.
Create Xcode project with Core Data
First, create a new Xcode project (with Core Data checkbox checked) with an imageView and two buttons. Create an @IBOutlet for the image and @IBActions for the buttons, and name accordingly. One button will be used for saving the image, the other will be used for retrieving the image:


Next, add another button that will cover the entire image area and an @IBAction for that button. Remove the title for the button in the Attributes inspector. You may have to ctrl-click and drag from the document outline’s button to the view controller code window.
The user will tap anywhere in the image area to bring up the Image Picker:

For the placeholder image, just grab any available placeholder image and place in the assets file. Make this the default image by selecting it in the Attributes inspector. Again, you may have to first select the image from the document outline since the button is covering the image in the storyboard:

Create Core Data Entity
Next, we’ll create a single entity in core data with an ‘image’ attribute. Open the model file and add an entity named ‘Photo’ with an attribute of ‘image’. Select the data type of ‘binary data’ for the image attribute. With the ‘Photo’ model selected, go to the Data Model inspector on the right and for ‘codegen’, select manual mode:


Create the NSManagedObject subclass fro the Editor menu:

Import Core Data at top of View Controller file.
Add two vars: 1 for the UIImagePicker and one for the array of photos that will be returned from fetching the Photo entities:

Add an extension for the view controller that conforms to UIImagePickerControllerDelegate. Configure the methods as below:

Next, add the method to open the image picker to the button action:

Run the app and try out the image picker:


Saving the image to Core Data
Add the following code for the save image action:

This code allows us to create an instance of the photo entity with the image attribute and save to Core Data.
Retrieving the image
Add the following code to the retrieve image action to retrieve the last image in the array of Photo images:

Run the app and select an image. After the image is selected, click on ‘save image’ button. Close and restart the app. Select the retrieve image button. It should retrieve the image from Core Data and load in the imageView.