【问题标题】:Download Image for CoreData下载 CoreData 的图像
【发布时间】:2019-09-07 22:32:46
【问题描述】:

我正在尝试创建多个包含名称和图像的 CoreData 对象,但该对象未保存。如果我将保存命令放在 URLSession 之外,则不会加载图片。还有其他选择吗?

让上下文 = self.appDelegate.persistentContainer.viewContext

let newDeputy = Deputy(context: context)
newDeputy.name = "someName"

URLSession.shared.dataTask(with: URL(string: deputy.personal.picture!.url)!) { data, response, error in
    if data != nil {
        if let imageData = UIImage(data: data!)!.jpegData(compressionQuality: 0.3) {
            newDeputy.picture = imageData
        }
    }

    do {
        try newDeputy.managedObjectContext?.save()
        print("SAVED \(newDeputy.name)")
    } catch let error as NSError {
        print("Couldnt save Deputy (\(newDeputy.name ?? "")) - \(error.localizedDescription)")
    }
}.resume()

【问题讨论】:

  • data 的类型似乎是 Optional,因为您在代码行中强制解包 if let imageData = UIImage(data: data!)!...。对if data != nil 的检查将始终为真。 (坦率地说,Xcode 并没有抱怨这一点。)我建议你重写你的代码,以确保 data 的值具有可以作为图像处理的数据。例如。 if let sessionData = data {}。使用断点和/或print() 到终端检查属性值。
  • 我通过简单地将整个东西移动到 URLSession 中来修复它:D

标签: swift core-data


【解决方案1】:

URLSession 中的每个任务都将在不同的线程上运行。因此,当您尝试将数据保存到 Core Data 时,您必须移至主线程。 Core Data 默认不是线程安全的(你可以让它成为线程安全的。)所以你必须在单线程中完成所有的获取和保存逻辑。

URLSession.shared.dataTask(with: URL(string: deputy.personal.picture!.url)!) { data, response, error in
if data != nil {
    if let imageData = UIImage(data: data!)!.jpegData(compressionQuality: 0.3) {
        newDeputy.picture = imageData
        DispatchQueue.main.async {
            newDeputy.picture = imageData
            do {
                try newDeputy.managedObjectContext?.save()
                print("SAVED \(newDeputy.name)")
            } catch let error as NSError {
                print("Couldnt save Deputy (\(newDeputy.name ?? "")) - \(error.localizedDescription)")
            }
        }
    }
}
}.resume()

【讨论】:

    猜你喜欢
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-02
    • 2014-11-07
    • 2016-04-09
    • 1970-01-01
    相关资源
    最近更新 更多