首页 > 解决方案 > How to save and fetch VideoURL in iOS swift using core data?

问题描述

I have a videoURL like file:///var/mobile/Containers/Data/Application/3C80B7F1-F0AA-4723-B7F5-E7AC5E71CA09/Documents/2018-Nov-12%2014:09:01output.mov

I am saving this videoURL by using below code as converting to DATA.

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

let entity = NSEntityDescription.entity(forEntityName: "Device", in: context)

let newEntity = NSManagedObject(entity: entity!, insertInto: context)

self.videoData =  NSData(contentsOf: self.videoURL as URL)! as Data

newEntity.setValue(self.videoData, forKey:"videoURL")

do {

    try context.save()
    print("saved")

} catch {
    print("not saved") 
}

but I am unable to converting this data to url while fetching. Could anyone guide me how to do this task?

标签: iosiphoneswift

解决方案


You are saving the loaded video data, not the URL.

Set the type of the attribute videoURL to URI and the type of the corresponding property to URL and save self.videoURL

By the way, don't use NS classes like NSURL and NSData, use URL and Data and it's highly recommended to use dot notation rather than KVC (value(forKey:) when accessing NSManagedObject properties

let newEntity = NSManagedObject(entity: entity!, insertInto: context) as! Device
self.videoData = Data(contentsOf: self.videoURL)! 

newEntity.videoURL = self.videoURL

do { 
    try context.save()
    print("saved")
} catch {
  print(error) 
}

推荐阅读