Storing images to CoreData - Swift

2019-01-23 09:33发布

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!

4条回答
Anthone
2楼-- · 2019-01-23 10:07

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

查看更多
地球回转人心会变
3楼-- · 2019-01-23 10:09

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":

enter image description here

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:

let image = UIImage(named: "YourImage")
let imageData = NSData(data: UIImageJPEGRepresentation(image, 1.0))
managedObject?.setValue(imageData, forKey: "YourKey")

Remember that 1.0 in the UIImageJPEGRepresentatio means that your using the best quality and so the image will be large and heavy:

The quality of the resulting JPEG image, expressed as a value from 0.0 to 1.0. The value 0.0 represents the maximum compression (or lowest quality) while the value 1.0 represents the least compression (or best quality).

查看更多
Deceive 欺骗
4楼-- · 2019-01-23 10:13

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.

let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String
// self.fileName is whatever the filename that you need to append to base directory here.
let path = documentsDirectory.stringByAppendingPathComponent(self.fileName)
let success = data.writeToFile(path, atomically: true)
if !success { // handle error }

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.

查看更多
霸刀☆藐视天下
5楼-- · 2019-01-23 10:25

Here you go for JPEG and for PNG you just use UIImagePNGRepresentation:

let image = UIImage(named: "YourImage")
let imageData = NSData(data: UIImageJPEGRepresentation(image, 1.0))
managedObject?.setValue(imageData, forKey: "YourKey")
查看更多
登录 后发表回答