Cannot save image thumbnail in Core Data using Swift

I have an entity attribute of type NSData to store an image thumbnail in a Core Data model. In my view controller I can select an image from my iPhone 6 simulator photo library, shrink it to a thumbnail using a UIImage extension and pull it into a UIImageView on my storyboard. So far, so good.


I know I have to convert it to NSData to save it in Core Data, but no matter what I do I just can't seem to manage it. My TextFields are all being passed to Core Data and retrieved again, but not the ImageView. Could someone please assist with some example code? I'm still learning Swift, so please be gentle!!!

If you could clarify, are you having problems with converting from UIImage to NSData, or with getting the NSData to be saved to Core Data? I can't help with the second part, but for the first you should be able to use UIImageJPEGRepresentation(YourImageView.image!) or UIImagePNGRepresentation(YourImageView.image!), which both return NSData objects. Best practice would be to check and make sure YourImageView.image is not nil before force unwrapping it using an if let... or if... statement.

Hi Norton,


Hopefully this will be useful. You can save the thumbnail to Core Data as a property on your model configured as Binary Data.


To get the image into a binary data format just assign the output to your property:

NSData * UIImageJPEGRepresentation ( UIImage *image, CGFloat compressionQuality );
NSData * UIImagePNGRepresentation ( UIImage *image );
Cannot save image thumbnail in Core Data using Swift
 
 
Q