SwiftUI CloudKit 在保持活动状态时不刷新视图

dav*_*dev 5 core-data ios icloud swift swiftui

我正在使用 SwiftUI 开发 macOS 和 iOS 应用程序。两者都使用 CoreData 和 iCloudKit 在两个平台之间同步数据。它确实与同一个 iCloud 容器配合得很好。

我遇到一个问题,即停留在应用程序中时不会触发 iCloud 后台更新。如果我在两个系统上进行更改,则会推送更改,但在其他设备上不可见。

我需要重新加载应用程序、关闭应用程序并再次打开,或者在 Mac 应用程序中失去焦点并返回到它。然后我的List就会刷新。我不知道为什么它不起作用,同时留在应用程序内而不失去焦点。

我在 Stackoverflow 上读到了几个线程,但是它们对我不起作用。这是我在 iOS 中的简单视图

struct ContentView: View {
    
    @Environment(\.managedObjectContext) var managedObjectContext
    
    @State private var refreshing = false
    private var didSave =  NotificationCenter.default.publisher(for: .NSManagedObjectContextDidSave)

    @FetchRequest(entity: Person.entity(), sortDescriptors: []) var persons : FetchedResults<Person>
    
    var body: some View {
        NavigationView
        {
            List()
            {
                ForEach(self.persons, id:\.self) { person in
                    Text(person.firstName + (self.refreshing ? "" : ""))
                    // here is the listener for published context event
                    .onReceive(self.didSave) { _ in
                        self.refreshing.toggle()
                    }
                }
            }
            .navigationBarTitle(Text("Person"))
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在此示例中,我已经使用了一种解决方法,并在另一个问题中描述了Asperi 。然而,这对我来说也不起作用。该列表不会被刷新。

在日志中我可以看到它没有 ping iCloud 进行刷新。仅当我重新打开应用程序时。为什么后台模式不起作用?我已正确激活所有内容并设置我的 AppDelegate。

lazy var persistentContainer: NSPersistentCloudKitContainer = {
    /*
     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.
    */
        
    container.persistentStoreDescriptions.forEach { storeDesc in
        storeDesc.shouldMigrateStoreAutomatically = true
        storeDesc.shouldInferMappingModelAutomatically = true
    }
    //let container = NSPersistentCloudKitContainer(name: "NAME")

    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.automaticallyMergesChangesFromParent = true
    container.viewContext.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy
    
    UIApplication.shared.registerForRemoteNotifications()
    
    return container
}()
Run Code Online (Sandbox Code Playgroud)

编辑:

我的 iOS 应用程序仅在重新打开应用程序时不断从 iCloud 获取记录。看这个动图:

and*_*der 3

因此,除了我的评论和没有更多信息之外,我怀疑您没有正确设置您的项目。

在签名和功能下,您的项目应该与此类似......

项目签约及能力

如前所述,我怀疑 ContentView 视图中的很多代码都是不必要的。尝试删除通知并简化您的视图代码,例如......

struct ContentView: View {
    
    @Environment(\.managedObjectContext) var managedObjectContext

    @FetchRequest(entity: Person.entity(), 
                  sortDescriptors: []
    ) var persons : FetchedResults<Person>
    
    var body: some View {
        
        NavigationView
        {
            List()
            {
                ForEach(self.persons) { person in
                    Text(person.firstName)
                }
            }
            .navigationBarTitle(Text("Person"))
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

正确设置项目后,CloudKit 应该处理必要的通知和@FetchRequest属性包装器将更新您的数据集。

另外,因为默认情况下每个核心数据实体都是Identifiable,所以不需要id:\.selfForEach语句中引用,所以而不是......

ForEach(self.persons, id:\.self) { person in
Run Code Online (Sandbox Code Playgroud)

你应该能够使用...

ForEach(self.persons) { person in
Run Code Online (Sandbox Code Playgroud)

正如评论中提到的,您在var persistentContainer. 它应该像这样工作...

lazy var persistentContainer: NSPersistentCloudKitContainer = {
        
    let container = NSPersistentCloudKitContainer(name: "NAME")

    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            // Replace this implementation with code to handle the error appropriately.
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    
    container.viewContext.automaticallyMergesChangesFromParent = true
    container.viewContext.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy
            
    return container
}()
Run Code Online (Sandbox Code Playgroud)