SwiftStarter
SwiftStarter

Reputation: 247

Converting image to NSData to save in core data

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

My core data 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 core data 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.

Upvotes: 1

Views: 1261

Answers (1)

Martin R
Martin R

Reputation: 539745

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.

Upvotes: 5

Related Questions