SwiftStarter SwiftStarter - 3 months ago 31
iOS Question

converting image to NSData to save in core data

I'm trying to store an image in core data.

My coredata properties file requires the image to be in NSData:

import Foundation
import CoreData

extension Item {

@nonobjc public class func fetchRequest() -> NSFetchRequest<TaskItem> {
return NSFetchRequest<TaskItem>(entityName: "Item");

@NSManaged public var itemImage: NSData?

However when I'm trying to save to coredata using:

@IBAction func saveBtnTapped(_ sender: AnyObject) {

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

let item = Item(context: context)

let imageData: NSData = UIImageJPEGRepresentation(taskImage.image!, 0.2)

item.itemImage = imageData

(UIApplication.shared.delegate as! AppDelegate).saveContext()

navigationController?.popViewController(animated: true)

I get the following error:

Cannot convert value of type 'Data?' to specified type 'NSData'

I thought I was doing it right, but it's not working for me. Could someone please give me an idea of how to fix it?

Thanks in advance.


UIImageJPEGRepresentation returns a Data? value. This can be bridged to NSData? with as. Then use optional binding (if let) to safely unwrap the optional:

if let imageData = UIImageJPEGRepresentation(...) as NSData? {
     // Now `imageData` is a `NSData` object.
     item.itemImage = imageData
} else {
     // Conversion to JPEG data failed.

You should also consult the section "Binary Large Data Objects (BLOBs)" in the "Core Data Programming Guide" about the implications of storing binary data directly in the database, and possible alternatives.