我有一个将 Core Data 与 CloudKit 一起使用的应用程序。更改在设备之间同步。主要目标具有背景模式功能,选中 Remote notifications
, iCloud 功能是通过将服务设置为 CloudKit 并检查容器中的正确容器来检查的。
我如何在代码中对记录的更改、删除和添加使用react?我需要调用WidgetCenter.shared.reloadAllTimelines()
当 CloudKit 中的 Core Data 更改以更新 iOS 14 主屏幕 WidgetKit 时。
我的目标是让它工作:我在 icloud.developer.apple.com 或其他设备上更改/添加/删除记录,以及 WidgetCenter.shared.reloadAllTimelines()
调用以在 WidgetKit 中显示正确的数据。应用程序可能在后台或前台。
来自 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> - Ignoring remote change notification because the exporter has already caught up to this transaction: 64 / 64 - <NSSQLCore: 0x100b09440> (URL: file:///var/mobile/Containers/Data/Application/F83C68DA-7C36-42CC-926D-7C721C679579/Library/Application%20Support/AppTitle.sqlite)
最佳答案
如果您想订阅 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()
太频繁了 - 您的 WidgetKit 可用的更新数量可能有限。
关于swift - CloudKit中的Core Data发生变化时如何调用WidgetCenter.shared.reloadAllTimelines()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63970726/