我正在运行一个URLSession数据任务来异步下载一些数据 - 然后将其插入到核心数据(可以是大约2000个项目)。将数据保存到数据库会冻结UI。在此看到其他帖子。我错过了什么?
self?.api.getData(param1, param2: id, success: { (data) -> Void in
let myData = JSON(data!)["Data"]
self?.insertDataToDb(myData){result in ...
...
func insertDataToDb(_ data: JSON, success: @escaping SuccessClosure, failure: @escaping FailureClosure){
let privateMOC = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
privateMOC.parent = context
privateMOC.perform {
self.insertJSONdata(data[Keys.FirstData])
do {
try privateMOC.save()
self.context.performAndWait {
do {
try self.context.save()
success()
} catch let error as NSError {
failure(error)
}
}
} catch let error as NSError {
failure(error)
}
}
}
答案 0 :(得分:0)
更新主线程中的UI
DispatchQueue.main.async {
self.updateUI()
}