Ada*_*aya 10 json background core-data ios swift
我正在使用Xcode 9和Swift 4.当应用程序在前台时,我开始下载多个JSON文件.然后,应用程序解析这些文件并将它们保存到CoreData.当应用程序位于前台时,这很有效.但是,如果应用程序在后台,文件仍然可以正确下载,但数据不会被解析并保存到CoreData.只有当用户返回到前台时,才会继续解析和保存数据.
我打开了后台模式 - 后台获取和远程通知.
我有大约10个类似下面的函数,它们同时处理JSON文件:
func populateStuff(json: JSONDictionary) -> Void {
let results = json["result"] as! JSONDictionary
let stuffData = results["Stuff"] as! [JSONDictionary]
let persistentContainer = getPersistentContainer()
persistentContainer.performBackgroundTask { (context) in
for stuff in stuffData {
let newStuff = Stuff(context: context)
newStuff.stuffCode = stuff["Code"] as? String
newStuff.stuffDescription = stuff["Description"] as? String
do {
try context.save()
} catch {
fatalError("Failure to save context: \(error)")
}
}
}
}
func getPersistentContainer() -> NSPersistentContainer {
let persistentContainer = NSPersistentContainer(name: "MyProjectName")
persistentContainer.loadPersistentStores { (_, error) in
if let error = error {
fatalError("Failed to load core data stack: \(error.localizedDescription)")
}
}
persistentContainer.viewContext.automaticallyMergesChangesFromParent = true
persistentContainer.viewContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
return persistentContainer
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以告诉我为什么会发生这种情况以及如何解决这个问题?
TIA
使用beginBackgroundTaskWithName:expirationHandler:方法:
func populateStuff(json: JSONDictionary) -> Void {
// Perform the task on a background queue.
DispatchQueue.global().async {
// Request the task assertion and save the ID.
self.backgroundTaskID = UIApplication.shared.beginBackgroundTask (withName: "Finish Network Tasks") {
// End the task if time expires.
UIApplication.shared.endBackgroundTask(self.backgroundTaskID!)
self.backgroundTaskID = UIBackgroundTaskInvalid
}
// Parse the json files
let results = json["result"] as! JSONDictionary
let stuffData = results["Stuff"] as! [JSONDictionary]
let persistentContainer = getPersistentContainer()
persistentContainer.performBackgroundTask { (context) in
for stuff in stuffData {
let newStuff = Stuff(context: context)
newStuff.stuffCode = stuff["Code"] as? String
newStuff.stuffDescription = stuff["Description"] as? String
do {
try context.save()
} catch {
fatalError("Failure to save context: \(error)")
}
}
}
// End the task assertion.
UIApplication.shared.endBackgroundTask(self.backgroundTaskID!)
self.backgroundTaskID = UIBackgroundTaskInvalid
}
Run Code Online (Sandbox Code Playgroud)
调用此方法将使您有更多时间执行重要任务。endBackgroundTask:在任务完成后立即注意方法的使用。它使系统知道您已完成。如果您不及时结束任务,系统将终止您的应用程序。
| 归档时间: |
|
| 查看次数: |
382 次 |
| 最近记录: |