【发布时间】: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