Ошибки NSPersistentCloudKitContainer - не синхронизируются c объекты изменены в автономном режиме - PullRequest
0 голосов
/ 24 апреля 2020

Я тестирую свою реализацию CoreData + CloudKit Syn c, используя NSPersistentCloudKitContainer, и иногда кажется, что она работает нормально. Я исправил проблему с пользователями, которые включали / выключали iCloud в настройках, как рекомендовано Apple, но теперь у меня проблема в том, что когда я тестирую свое приложение в автономном режиме, когда я снова в сети с подключением inte rnet, нет синхронизации У меня есть некоторый код, который правильно запускает и обнаруживает наличие соединения inte rnet или нет ... но все же не похоже, что установка параметров контейнера на nil и затем обратно в контейнер cloudkit заставляет его синхронизироваться c. Вот мой код:

lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded 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.
        */

        let container : NSPersistentContainer?
        container = NSPersistentCloudKitContainer(name: "Model")

        let description = NSPersistentStoreDescription(url: applicationDocumentsDirectory()!.appendingPathComponent("Model.sqlite"))
        description.setOption(true as NSNumber,forKey: NSPersistentHistoryTrackingKey)

        //Check if user is first logged onto iCloud enabled/not - if not then set cloudkitcontainer options to nil to disable sync and use the local DB on device

        // This was from an accepted answer here: https://forums.developer.apple.com/thread/118924
        //NB This works and the code here is triggered because a switch on/off icloud in settings kills the app and makes it restart, so this code is triggered.
        if FileManager.default.ubiquityIdentityToken != nil { //logged onto iCloud*/


                       description.cloudKitContainerOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: "iCloud.com.my.container")
        } else {

            description.cloudKitContainerOptions = nil;

        }

        //However, turning a device to airplane mode on/off won't kill the app to trigger the above code, so have to put that check in with checking when the device is on or offline:
        monitor.pathUpdateHandler = { path in
            if path.status == .satisfied {
                description.cloudKitContainerOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: "iCloud.com.my.container")

            } else {
                description.cloudKitContainerOptions = nil

            }

        }


        //ensure migration------

        description.shouldInferMappingModelAutomatically = true
        description.shouldMigrateStoreAutomatically = true

        //----------------------

        container!.persistentStoreDescriptions = [description]

        container!.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() 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.

                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */


                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })

        container!.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
        container!.viewContext.automaticallyMergesChangesFromParent = true
        return container!
    }()

Редактировать

Я только что попробовал это с устройства на устройство, и, кажется, работает, если одно устройство мгновенно переводится в автономный режим без активированного экземпляра монитора (закомментировал этот бит кода для тестирования). Однако, если устройство переводится в режим полета на длительный период времени, создается впечатление, что обновления CloudKit не отправляются и синхронизируются с другим устройством, а не с последним изменением с устройства, на котором я работаю ...

...