swift - CloudKit中的Core Data发生变化时如何调用WidgetCenter.shared.reloadAllTimelines()?

标签 swift core-data swiftui cloudkit widgetkit

我有一个将 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/

相关文章:

iphone - Child 的 child 的反向关系

objective-c - CoreData中的NSDate是否封装了时区?

ios - 在 SwiftUI 中添加圆角半径时如何隐藏背景颜色的溢出?

swift - 触摸时如何使 UIButton 边框闪烁

ios - 以编程方式创建 UIViewController 不显示 subview 或识别手势

ios - CoreData 与子类的关系

SwiftUI 在详细 View 中覆盖导航栏外观

foreach - SwiftUI:如何使用 ForEach 选择多个项目(图像)?

ios - 在 Realm-Swift 中创建数据库

swift - 如何在swift语言中输入cast