Search code examples
swiftcore-datauiimagepngrepresentation

Unable to load/retrieve image from Core Data


I've searched the internet all day for a solution, not getting anywhere.. I am saving an image to core data which when tested using print(results) with NSFetchRequest, suggests is stored in the Core Data by showing the following in 'debug area'...

[<toootesting.Entity: 0x7fb0816a69f0> (entity: Entity; id: 0xd000000000040000 <x-coredata://2D52E511-B03F-4629-ADF1-DEBD80A63EC0/Entity/p1> ; data: { photo = <89504e47 0d0a1a0a 0000000d 49484452 0000021c 000001e4 08020000 00fab561 c2000000 01735247 4200aece 1ce90000 0009>;

The image is saved using the following code...

 @IBAction func buttonOne(sender: AnyObject) {

    let img = UIImage(named: "Fencing")

    self.imageViewOne.image = img
    let imgData = UIImagePNGRepresentation(img!)

    let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let context: NSManagedObjectContext = appDel.managedObjectContext

    var newPhotos = NSEntityDescription.insertNewObjectForEntityForName("Entity", inManagedObjectContext: context)

    newPhotos.setValue(imgData, forKey: "photo")

    do {
        try context.save()
        print("image saved")

    } catch {
        print("error - saving NSData Image")
    }
}

However, when I try Loading the saved CoreData image onto a 2nd imageView the fetch request comes up with an error...."Cannot convert value of type[AnyObject] to expected argument type NSData"

The code is...

@IBAction func loadButton(sender: AnyObject) {

    let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let context: NSManagedObjectContext = appDel.managedObjectContext

    let request = NSFetchRequest(entityName: "Entity")
    request.returnsObjectsAsFaults = false

    do {
        let results = try context.executeFetchRequest(request)

        print(results)

        self.imageViewTwo?.image = UIImage(data: results)

    } catch {
        print("error - Loading!!!")
    }
}

It seems I can convert UIImage in the 1st action to NSData, but on Fetch, unable to convert NSData back to UIImage in order to show it on viewController.

My question is if I can convert from UIImage to NSData easily, should I be able to do vice versa in same way? What is stopping the code from showing the image? A coding solution would be much appreciated.

Many thanks for your help in advance, as I am a new starter here.


Solution

  • The fetch request returns an array. You have to

    • extract the first object
    • cast to NSData

    Thus:

    let results = try context.executeFetchRequest(request) as! [Entity]
    let imageData = results.first!.photo
    

    Note that in shipping code you should avoid to force-unwrapping optionals.
    The above applies that you have subclassed NSManagedObject to describe the Entity entity.