3

我有一个将 Core Data 与 CloudKit 一起使用的应用程序。更改在设备之间同步。主要目标具有背景模式功能,已检查Remote notifications,iCloud 功能已检查,服务设置为 CloudKit 并检查容器中的正确容器。

我如何在代码中对记录的更改、删除和添加做出反应?WidgetCenter.shared.reloadAllTimelines()当 CloudKit 中的核心数据更改以更新 iOS 14 主屏幕小部件时,我需要调用。

我的目标是让它工作:我在 icloud.developer.apple.com 或其他设备上更改/添加/删除记录,并WidgetCenter.shared.reloadAllTimelines()调用以在小部件中显示正确的数据。应用程序可能在后台或前台。

来自AppDelegate.swift

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Register for Remote Notifications
    application.registerForRemoteNotifications()
    
    return true
}

此外,在输出日志中注意到消息:

CoreData: debug: CoreData+CloudKit: -[NSCloudKitMirroringDelegate remoteStoreDidChange:]_block_invoke(2138): <NSCloudKitMirroringDelegate: 0x281818d00> - 忽略远程更改通知,因为出口商已经赶上了这个事务:64 / 64 - <NSSQLCore: 0x100b09440> (网址:file:///var/mobile/Containers/Data/Application/F83C68DA-7C36-42CC-926D-7C721C679579/Library/Application%20Support/AppTitle.sqlite)

4

1 回答 1

5

如果您想订阅 Core Data 远程通知,您可以使用onReceive

struct WidgetEntryView : View {
    var entry: Provider.Entry

    var body: some View {
        Text(entry.date, style: .time)
            .onReceive(NotificationCenter.default.publisher(for: .NSPersistentStoreRemoteChange)) { _ in
                // make sure you don't call this too often
                WidgetCenter.shared.reloadAllTimelines()
            }
    }
}

只要确保您不要reloadAllTimelines()经常打电话 - 您的小部件可用的更新数量可能有限。

于 2020-09-19T16:47:19.063 回答