首页 > 解决方案 > 使用 SwiftUI 和 Core Data 镜像 CloudKit 进行屏幕更新

问题描述

当通过 cloudkit 同步新信息时,我在获取更新视图时遇到问题。在两台设备上运行此应用时,如果设备 A 添加调色板,则仅在应用重新启动时才会出现在设备 B 上。我已经查看了有关堆栈溢出的其他一些答案,但没有一个有效。有人有什么主意吗?

这是我来自 AppDeligate 的持久容器

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

        // get the store description
        guard let description = container.persistentStoreDescriptions.first else {
            fatalError("Could not retrieve a persistent store description.")
        }

        // initialize the CloudKit schema
        let id = "iCloud.com.peterfoxflick.swatch"
        let options = NSPersistentCloudKitContainerOptions(containerIdentifier: id)
        description.cloudKitContainerOptions = options
        
        let remoteChangeKey = "NSPersistentStoreRemoteChangeNotificationOptionKey"
        description.setOption(true as NSNumber,
                                   forKey: remoteChangeKey)
        
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        
        container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
        container.viewContext.automaticallyMergesChangesFromParent = true
        
        return container
    }()

而我的看法

struct PalettesListView: View {
    @EnvironmentObject var palettesList: PalettesListViewModel
    
    let pub = NotificationCenter.default
            .publisher(for: NSNotification.Name("NSPersistentStoreRemoteChangeNotificationOptionKey"))


    var body: some View {
        NavigationView {
            List{
                    ForEach(self.palettesList.palettes){ p in
                            Text(p.name)
                                .font(.headline)
                         
                    }

                }
            }
            .onReceive(pub) { (output) in
                self.palettesList.fetch()
      }
}

struct SwatchesListView_Previews: PreviewProvider {
    static var previews: some View {
        PalettesListView()
    }
}

我也尝试将相同的侦听器添加到我的 ViewModel 但没有运气。如果您想查看所有代码,可以查看 GitHub

PS。某些括号/格式可能已关闭,我将代码缩减为相关部分。

标签: swiftcore-dataswiftuicloudkit

解决方案


你的合并策略是让本地更改胜过远程更改。尝试删除它或使用不同的合并策略。


推荐阅读