应用程序卸载/重新安装后 CoreData + Cloudkit fetch() 不返回任何结果

pro*_*ons 6 core-data ios swift cloudkit nspersistentcloudkitcontainer

我正在尝试配置 CoreData+CloudKit 以NSPersistentCloudKitContainer自动将数据同步到 CloudKit 或从 CloudKit 同步数据。

按照Apple 指南,设置一个实体、在 Xcode 中添加适当的功能、在我的 AppDelegate 中设置persistentContainer和就足够简单了。saveContext

我通过 拨打fetch()save()拨打电话NSManagedObjectContext,并且能够毫无问题地保存和获取记录。我可以在 CloudKit 仪表板中看到它们。

但是,如果我从模拟器中卸载应用程序并重建/重新安装,我的应用程序fetchRequest(没有排序NSPredicate或排序,只是获取所有记录)始终返回一个空列表。我使用相同的 iCloud 帐户,并且尝试了公共和私有数据库范围。如果我创建一条新记录,然后重试我的提取请求,我可以检索该新创建的记录,但永远不会检索任何旧记录。我 100% 确定这些记录仍在 CloudKit 数据库中,因为我可以在 CloudKit Dashboard Web 应用程序上看到它们。

我查看了Apple 的 CoreDataCloudKitDemo应用程序,它能够在卸载/重新安装后从 CloudKit 数据库中获取“Post”实体,所以我知道这是可能的。但是,它使用的是NSFetchedResultsController,这不适用于我的应用程序(我的应用程序是 SpriteKit 游戏)。

我尝试将 CoreData+Cloudkit 代码复制到一个全新的 Xcode 项目中,我可以在那里重现此问题。这是我的代码供参考:

import UIKit
import CoreData

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    lazy var persistentContainer: NSPersistentContainer = {

        // Create a container that can load CloudKit-backed stores
        let container = NSPersistentCloudKitContainer(name: "coredatacloudkitexample")

        // Enable history tracking and remote notifications
        guard let description = container.persistentStoreDescriptions.first else {
            fatalError("###\(#function): Failed to retrieve a persistent store description.")
        }
        description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
        description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
        description.cloudKitContainerOptions?.databaseScope = .public

        container.loadPersistentStores(completionHandler: { (_, error) in
            guard let error = error as NSError? else { return }
            fatalError("###\(#function): Failed to load persistent stores:\(error)")
        })

        container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
        container.viewContext.transactionAuthor = "nibbler"

        // Pin the viewContext to the current generation token and set it to keep itself up to date with local changes.
        container.viewContext.automaticallyMergesChangesFromParent = true
        do {
            try container.viewContext.setQueryGenerationFrom(.current)
        } catch {
            fatalError("###\(#function): Failed to pin viewContext to the current generation:\(error)")
        }

        return container
    }()
}


// ------

import UIKit
import CoreData

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        let viewContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        let fetchRequest: NSFetchRequest<Person> = Person.fetchRequest()
        let people: [Person]

        do {
            people = try viewContext.fetch(fetchRequest)
            print("---> fetched People from CoreData: \(people)")

            // people.isEmpty is ALWAYS true (empty array) on first install of app, even if records exist in table in CloudKit
            if people.isEmpty {
                let person = Person(context: viewContext)
                person.name = "nibbler"

                // save the data through managed object context
                do {
                    try viewContext.save()
                    print("--> created Person in CoreData: \(person)")
                } catch {
                    print("---> failed to save Person: \(error.localizedDescription)")
                }
            }
        } catch {
            print("---> error: \(error)")
        }
    }
}


Run Code Online (Sandbox Code Playgroud)

我缺少什么?为什么我只能获取此应用程序安装期间创建的记录,而不能获取之前的记录?

更新:似乎如果我等待几秒钟并在第一个应用程序安装上重新尝试获取,我可以从 CloudKit 数据库中检索结果。CoreData+CloudKit首次启动时我还可以在控制台中看到大量日志消息。这就是我的想法 - 即使使用时NSPersistentCloudKitContainer, afetch()也会读取/写入本地 CoreData 存储,然后在后台运行一个单独的进程来镜像并将本地 CoreData 记录与 CloudKit 记录合并。

因此,我相信我需要以某种方式等待/收到通知,告知本地 CoreData 和 CloudKit 记录的同步/合并已在首次启动时完成fetch(),然后再进行调用,而不是fetch()在应用程序打开时立即进行调用。有任何想法吗?

mal*_*hal 5

您需要使用NSFetchedResultsController,为什么您认为它不适用于您的应用程序?

其必要的原因是NSFetchedResultsController监视,viewContext并且当同步过程下载新对象并将它们插入到后台上下文中时,将automaticallyMergesChangesFromParent对象合并到viewContext并推进生成令牌。如果从获取的对象数组中插入、更新或删除对象,则调用 FRC 的委托方法来通知您,这些对象是上下文中与获取请求的实体和谓词相匹配的对象。