从CloudKit获取并保存到CoreData

时间:2016-01-28 04:23:40

标签: ios swift core-data cloudkit

这将是一个真正的noob问题,但我试图让我的应用程序从CloudKit下载数据,然后将其保存到CoreData。

当我运行这种类型的代码时,我收到以下错误。我是CoreData的老手,所以这对我来说很难理解。我认为这与我调度请求的方式有关,但我不确定我应该如何修复它。我得到的错误是:

  

由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:'recordChangeSnapshot:forObjectID :: global ID在录制时可能不是临时的   “

有人有什么想法吗?

import UIKit
import CloudKit
import CoreData

class Start: UIViewController {

    var classroomEN: String?
    var classroomTC: String?
    var classroomSC: String?

    var videos = [NSManagedObject]()

    override func viewDidLoad() {

        fetchData()
        fetchDataTC()
    }

    func fetchData() {

        //added to fetch data from CloudKit
        let container = CKContainer.defaultContainer()
        let publicData = container.publicCloudDatabase

        let predicate = NSPredicate(value: true)

        let queryEN = CKQuery(recordType: "ClassroomFAQEN", predicate: predicate)
        let queryTC = CKQuery(recordType: "ClassroomFAQTC", predicate: predicate)

        queryEN.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
        queryTC.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

        publicData.performQuery(queryEN, inZoneWithID: nil) { results, error in

            if error == nil { // There is no error

                for entry in results! {
                    let newFAQ = classFAQ()
                    newFAQ.title = entry["Title"] as! String
                    newFAQ.content = entry["Content"] as! String
                    if entry["Picture"] != nil {
                        print("There is no picture")
                        newFAQ.picture = entry["Picture"] as! String
                    }
                    if entry["Video"] != nil {
                        print("There is no video")
                        newFAQ.video = entry["Video"] as! String
                    }

                    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
                    let managedContext = appDelegate.managedObjectContext
                    let entity =  NSEntityDescription.entityForName("ClassroomFAQEN", inManagedObjectContext:managedContext)
                    let video = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)
                    video.setValue(newFAQ.title, forKey: "title")
                    video.setValue(newFAQ.content, forKey: "content")
                    video.setValue(newFAQ.picture, forKey: "picture")
                    video.setValue(newFAQ.video, forKey: "video")

                    do {
                        try video.managedObjectContext!.save()
                        self.videos.append(video)
                    } catch let error as NSError  {
                        print("Could not save \(error), \(error.userInfo)")
                    }

                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        print("Reloading data in tableView")
                        self.fetchDataTC()
                    })
                }
            }
            else {
                print(error)
            }
        }
    }

    func fetchDataTC() {

        //added to fetch data from CloudKit
        let container = CKContainer.defaultContainer()
        let publicData = container.publicCloudDatabase

        let predicate = NSPredicate(value: true)

        let queryEN = CKQuery(recordType: "ClassroomFAQEN", predicate: predicate)
        let queryTC = CKQuery(recordType: "ClassroomFAQTC", predicate: predicate)

        queryEN.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
        queryTC.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

        publicData.performQuery(queryTC, inZoneWithID: nil) { results, error in

            if error == nil { // There is no error

                for entry in results! {
                    let newFAQ = classFAQ()
                    newFAQ.title = entry["Title"] as! String
                    newFAQ.content = entry["Content"] as! String
                    if entry["Picture"] != nil {
                        print("There is no picture")
                        newFAQ.picture = entry["Picture"] as! String
                    }
                    if entry["Video"] != nil {
                        print("There is no video")
                        newFAQ.video = entry["Video"] as! String
                    }

                    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
                    let managedContext = appDelegate.managedObjectContext
                    let entity =  NSEntityDescription.entityForName("ClassroomFAQTC", inManagedObjectContext:managedContext)
                    let video = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)
                    video.setValue(newFAQ.title, forKey: "title")
                    video.setValue(newFAQ.content, forKey: "content")
                    video.setValue(newFAQ.picture, forKey: "picture")
                    video.setValue(newFAQ.video, forKey: "video")

                    do {
                        try video.managedObjectContext!.save()
                        self.videos.append(video)
                    } catch let error as NSError  {
                        print("Could not save \(error), \(error.userInfo)")
                    }

                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        print("Reloading data in tableView")
                    })
                }
            }
            else {
                print(error)
            }
        }

    }

1 个答案:

答案 0 :(得分:0)

您可以使用isMainThread来确定您是否在后台线程中..或者您可以直接编写这样的代码,这将始终确保它在主线程中: - < / p>

    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        do {
                        try video.managedObjectContext!.save()
                        self.videos.append(video)
                    } catch let error as NSError  {
                        print("Could not save \(error), \(error.userInfo)")
                    }
                    })