在 Swift 中将 CoreData 保存/同步到 iCloud

Posted

技术标签:

【中文标题】在 Swift 中将 CoreData 保存/同步到 iCloud【英文标题】:Saving/Syncing CoreData to iCloud in Swift 【发布时间】:2015-02-22 23:23:00 【问题描述】:

我无法将我的 CoreData 同步到 iCloud 我一直在控制台中出现错误提示 2015-02-22 23:09:31.229 Newstron[1711:233218] -[PFUbiquitySetupAssistant finishSetupWithRetry:](826): CoreData: Ubiquity: <PFUbiquitySetupAssistant: 0x7fbc6357e580>: Retrying after delay: 60 Error Domain=NSCocoaErrorDomain Code=134080 "The operation couldn’t be completed. (Cocoa error 134080.)" UserInfo=0x7fbc637794f0 Reason=Didn't get a container URL back from URLForUbiquityContainerIdentifier:, giving up now. Please ensure the application is signed with the proper entitlements to read from the container., NSPersistentStoreUbiquitousContainerIdentifierKey=null

我在 AppDelegate.swift 中有代码

// MARK: - Core Data stack
func observeCloudActions(persistentStoreCoordinator psc: NSPersistentStoreCoordinator?) 
    // iCloud notification subscriptions
    let nc = NSNotificationCenter.defaultCenter();
    nc.addObserver(
        self,
        selector: "storesWillChange:",
        name: NSPersistentStoreCoordinatorStoresWillChangeNotification,
        object: psc);

    nc.addObserver(
        self,
        selector: "storesDidChange:",
        name: NSPersistentStoreCoordinatorStoresDidChangeNotification,
        object: psc);

    nc.addObserver(
        self,
        selector: "persistentStoreDidImportUbiquitousContentChanges:",
        name: NSPersistentStoreDidImportUbiquitousContentChangesNotification,
        object: psc);

    nc.addObserver(
        self,
        selector: "mergeChanges:",
        name: NSManagedObjectContextDidSaveNotification,
        object: psc);


func mergeChanges(notification: NSNotification) 
    NSLog("mergeChanges notif:\(notification)")
    if let moc = managedObjectContext 
        moc.performBlock 
            moc.mergeChangesFromContextDidSaveNotification(notification)
            self.postRefetchDatabaseNotification()
        
    


func persistentStoreDidImportUbiquitousContentChanges(notification: NSNotification) 
    self.mergeChanges(notification);


// Subscribe to NSPersistentStoreCoordinatorStoresWillChangeNotification
// most likely to be called if the user enables / disables iCloud
// (either globally, or just for your app) or if the user changes
// iCloud accounts.
func storesWillChange(notification: NSNotification) 
    NSLog("storesWillChange notif:\(notification)");
    if let moc = self.managedObjectContext 
        moc.performBlockAndWait 
            var error: NSError? = nil;
            if moc.hasChanges && !moc.save(&error) 
                NSLog("Save error: \(error)");
             else 
                // drop any managed objects
            

            // Reset context anyway, as suggested by Apple Support
            // The reason is that when storesWillChange notification occurs, Core Data is going to switch the stores. During and after that switch (happening in background), your currently fetched objects will become invalid.

            moc.reset();
        

        // now reset your UI to be prepared for a totally different
        // set of data (eg, popToRootViewControllerAnimated:)
        // BUT don't load any new data yet.
    


// Subscribe to NSPersistentStoreCoordinatorStoresDidChangeNotification
func storesDidChange(notification: NSNotification) 
    // here is when you can refresh your UI and
    // load new data from the new store
    NSLog("storesDidChange posting notif");
    self.postRefetchDatabaseNotification();


func postRefetchDatabaseNotification() 
    dispatch_async(dispatch_get_main_queue(),  () -> Void in
        NSNotificationCenter.defaultCenter().postNotificationName(
            "kRefetchDatabaseNotification", // Replace with your constant of the refetch name, and add observer in the proper place - e.g. RootViewController
            object: nil);
    )


lazy var applicationDocumentsDirectory: NSURL = 
    // The directory the application uses to store the Core Data store file. This code uses a directory named "hyouuu.pendo" in the application's documents Application Support directory.
    let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
    return urls[urls.count-1] as! NSURL
    ()

lazy var managedObjectModel: NSManagedObjectModel = 
    // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
    let modelURL = NSBundle.mainBundle().URLForResource("MyAppData", withExtension: "momd")!
    NSLog("modelURL:\(modelURL)")
    return NSManagedObjectModel(contentsOfURL: modelURL)!
    ()

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = 
    // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
    // Create the coordinator and store
    var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("MyAppData.sqlite")
    NSLog("storeURL:\(url)")
    var error: NSError? = nil
    var failureReason = "There was an error creating or loading the application's saved data."
    if coordinator!.addPersistentStoreWithType(
        NSSQLiteStoreType,
        configuration: nil,
        URL: url,
        options: [NSPersistentStoreUbiquitousContentNameKey : "MyAppName"],
        error: &error) == nil
    
        coordinator = nil
        // Report any error we got.
        let dict = NSMutableDictionary()
        dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
        dict[NSLocalizedFailureReasonErrorKey] = failureReason
        dict[NSUnderlyingErrorKey] = error
        //error = NSError(domain: "Pendo_Error_Domain", code: 9999, userInfo: dict as! [NSObject : AnyObject])
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog("AddPersistentStore error \(error), \(error!.userInfo)")
    

    self.observeCloudActions(persistentStoreCoordinator: coordinator)

    return coordinator
    ()

lazy var managedObjectContext: NSManagedObjectContext? = 
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
    let coordinator = self.persistentStoreCoordinator
    if coordinator == nil 
        return nil
    
    var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
    managedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
    managedObjectContext.persistentStoreCoordinator = coordinator
    return managedObjectContext
    ()

// MARK: - Core Data Saving support

func saveContext () 
    if let moc = self.managedObjectContext 
        var error: NSError? = nil
        if moc.hasChanges && !moc.save(&error) 
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog("Unresolved error \(error), \(error!.userInfo)")
        
    

我不知道问题是什么代码签名看起来没问题,但我一直收到这个错误我在 Apple Developer Forms 上查看过没有答案,在溢出和谷歌上查看同样没有对我的问题的答案。关于我得到的那个错误没有那么多文档。那么有没有更好的方法来实现与 iCloud 集成的 CoreData,或者是否有解决这个问题的方法。 AppDelegate.swift 中的代码是我实现 iCloud 代码的唯一地方。

【问题讨论】:

您找到解决方案了吗?我在设置中禁用 iCloud 时正在测试同步,当我在 iCloud Drive 设置中关闭我的应用程序时看到相同的错误。这是有道理的,因为该应用程序已经与云同步,因此具有数据的本地副本,所以我怀疑该错误是由于在系统级别没有与容器重新同步的权限引起的。我想弄清楚的是,我是否需要对错误进行实际处理,或者只是忽略它。 【参考方案1】:

我也遇到过这个问题。 通过转到 Target / Capabilities 并打开 iCloud 并单击 iCloud Documents 复选框来修复它。 由于我的声誉太低,无法发布屏幕截图。

【讨论】:

我已经让它工作了,只需要在每次添加、更改或删除时进行同步。它同步的唯一时间是应用关闭时。 收到相同的消息,打开答案中的选项(在 Xcode 6.2.4 中)并开始连接。

以上是关于在 Swift 中将 CoreData 保存/同步到 iCloud的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Swift 3 中将自定义类保存为 CoreData 实体的属性?

在 Swift4 中将获取的 XMPPframeWork vCards 保存到 CoreData

如何在 Swift 中将字符串数组保存到 Core Data

如何在 Swift 中将可转换属性保存到 Core Data

如何在 Swift 中将 Core Data 与 Cloudkit 和许多设备同步

如何在 swift 2 中将 UITextField 保存到核心数据?