带请求的后台任务和CoreData保存

时间:2017-12-20 11:18:27

标签: ios swift core-data background

我需要执行一系列http请求并将结果保存在CoreData中。我还需要能够相应地背景应用程序,任务必须继续。我尝试在 UIApplication.shared.beginBackgroundTask UIApplication.shared.endBackgroundTask 之间附加任务,但在这种情况下,保存到CoreData不正确或不会发生(错误) 。 如何正确实现?

首先,我做了很多请求,然后在最后我调用saveContext并期望完成。我有跟随线,它在前台工作。

上下文

context = CoreDataManager.instance.persistentContainer.newBackgroundContext()

CoreDataManager

  class CoreDataManager {

    static let instance = CoreDataManager()

    private init() {}

    @available(iOS 10.0, *)
    lazy var persistentContainer: NSPersistentContainer = {

        let container = NSPersistentContainer(name: "Addresses")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error {

                fatalError("Unresolved error \(error)")
            }
        })
        return container
    }()

    func getContext () -> NSManagedObjectContext {
        var context: NSManagedObjectContext?

        if #available(iOS 10.0, *) {
            context = persistentContainer.viewContext
        } else {
            guard let modelURL = Bundle.main.url(forResource: "Addresses", withExtension:"momd") else {
                fatalError("Error loading model from bundle")
            }
            guard let mom = NSManagedObjectModel(contentsOf: modelURL) else {
                fatalError("Error initializing mom from: \(modelURL)")
            }
            let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
            let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
            let docURL = urls[urls.endIndex-1]
            let storeURL = docURL.appendingPathComponent("Addresses.sqlite")
            do {
                try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil)
            } catch {
                fatalError("Error migrating store: \(error)")
            }
            context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
            context?.persistentStoreCoordinator = psc
        }
        return context!
    }

    func saveContext(context: NSManagedObjectContext){
        if (context.hasChanges){
            context.performAndWait {
                do {
                    try context.save()
                } catch let error as NSError  {
                    print("Could not save \(error), \(error.userInfo)")
                } 
            }

        }
    }
}

简单请求

NetworkManager.sharedInstance.request(url).responseJSON(queue: queue){ response in
                                if (response.error == nil){
                                    let jsonDataImage: Data = response.data!
                                    do{
                                        if let jsonResultImage = try JSONSerialization.jsonObject(with: jsonDataImage, options: []) as? [String:AnyObject] {
                                            if (jsonResultImage["Status"] as! Int==0){
                                                let tasks = Tasks(context: context)
                                                let str = (jsonResultImage["task"] as! String)
                                                if let data = NSData(base64Encoded: str, options:NSData.Base64DecodingOptions.init(rawValue: 0)){
                                                    tasks.image = data
                                                }
                                                tasks.id = taskId
                                                tasks.name = (taskArray![j]["Custom"] as! NSString) as String
                                                tasks.place = (taskArray![j]["Place_ar"] as! NSString) as String
                                                tasks.shemeId = taskArray![j]["ShemeId"] as! Int32
                                            }
                                        }
                                    }catch{
                                        print(error)
                                    }
                                }
                            }

我离开 URLSessionConfiguration.default 和变量 queue - .utility (还)。

0 个答案:

没有答案