Storing photos and videos in Core Data?

那年仲夏 提交于 2019-11-30 02:32:00

For the photo:

UIImagePickerController will return us an UIImage inside the memory, so you wouldn't have to do anything, not taking it out of the user's photo library and save it in your core data...

For the video: You can take the data out using NSData *data = [NSData dataWithContentsOfFile:] or [NSData dataWithContentsOfUrl:] to get the NSData object of the video. You can get the videoUrl easily

So, I just corrected some of your wrong assumptions first.

You don't need to save it directly to CoreData. You can save it to your application's document folder and then users will not be able to delete it. Moreover, saving to the application's document folder and only save the link to CoreData will also save your soul from handling big data object.

The problem may be that you need to deal with your file storage.

I don't think there is a best practice here.

Saving in user's photo library will help the users see their photos and videos easier without accessing your app

Saving in CoreData may be easier for you and may be faster some time

Saving into file storage may help you not dealing with some binary problem when loading video because Apple MPMoviePlayerController may help you

For me, because I don't use much SQLite and Core Data, I choose to store into file system

Use Code Data to store images and big files.

Code Data can save binary data to disk for you automatically, just set this option on the properties of the attribute, you just need to activate the option to allow external storage and Core Data will do the magic for you, simple as that.

Here you are the function to do in Swift3

//Image
let imageData = UIImageJPEGRepresentation(image, 1) // You can low compression up to >0

//Video from URL
let videoData = NSData(contentsOf:videoURL!)

Its so simple! iOs sweet programming.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!