In my code I managed to save a textLabel with CoreData but I can't seem to properly save the image. I've read some tutorials and I know I have to convert it to NSData. But how do I do it?
Thanks in advance!
In my code I managed to save a textLabel with CoreData but I can't seem to properly save the image. I've read some tutorials and I know I have to convert it to NSData. But how do I do it?
Thanks in advance!
Generally large data objects are not stored in a database or Core Data. Instead save the images in the Document directory (or a sub-directory) and save the file name in Core Data.
Se the answer by @Valentin on how to create a data representation of an image.
Save it with
func writeToFile(_ path: String, atomically atomically: Bool) -> Bool
You shouldn't save large data inside core data, an Apple engineer told me this little trick at the last WWDC:
You can use the property "Allows external storage":
By doing this as far as i know, your image will be stored somewhere in the file system, and inside core data will be saved a link to your picture in the file system. every time you'll ask for the picture, core data will automatically retrive the image from the file system.
To save the image as NSData you can do:
Remember that 1.0 in the UIImageJPEGRepresentatio means that your using the best quality and so the image will be large and heavy:
Core Data isn't meant to save big binary files like images. Use Document Directory in file system instead.
Here is sample code to achieve that.
It is recommended to save
filename
part to core data along with other meta data associated with that image and retrieve from file system every time you need it.edit: also note that from ios8 onwards, persisting full file url is invalid since sandboxed app-id is dynamically generated. You will need to obtain
documentsDirectory
dynamically as needed.Here you go for JPEG and for PNG you just use UIImagePNGRepresentation: