【问题标题】:CoreData not updated until application inactivatesCoreData 在应用程序停用之前不会更新
【发布时间】:2022-04-25 03:45:11
【问题描述】:

我正在构建一个 Macos CoreData+CloudKit 应用程序。

我首先通过这样做来创建我的容器:

let container = NSPersistentCloudKitContainer(name: "TestApp")
let description = container.persistentStoreDescriptions.first
description?.setOption(true as NSNumber,
                       forKey: NSPersistentHistoryTrackingKey)
let remoteChangeKey = "NSPersistentStoreRemoteChangeNotificationOptionKey"
description?.setOption(true as NSNumber,
                           forKey: remoteChangeKey)
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
    if let error = error {
        fatalError("Unresolved error \(error)")
    }
})

我正在注册以通过以下方式接收远程更改:

NotificationCenter.default.addObserver(
            self,
            selector: #selector(fetchChanges),
            name: NSNotification.Name(
                rawValue: "NSPersistentStoreRemoteChangeNotification"),
            object: persistentContainer.persistentStoreCoordinator
        )

fetchChanges,我只是通过

重新加载我的用户界面
  1. 获取数据
  2. 重新加载我的 tableView

但是,我发现在应用程序停用之前,永远不会调用 fetchChanges。我在日志中看到:

CoreData: debug: CoreData+CloudKit: -[PFCloudKitThrottledNotificationObserver noteRecievedNotification:](40): <PFCloudKitThrottledNotificationObserver: 0x600003fb3fc0>: Got: NSApplicationWillBecomeActiveNotification - 0

我假设正在发生的事情是,当 CoreData 通过 NSApplicationWillBecomeActiveNotification 事件检测到我的窗口未激活时,它会生成一个后台任务以将远程 iCloud 数据提取到本地存储中。

此时,NSPersistantStoreRemoteChangeNotification 已收到。

我的问题是如何强制本地商店与iCloud同步?

非常感谢任何帮助。

【问题讨论】:

    标签: swift macos core-data cloudkit


    【解决方案1】:

    一些可能的线索:

    1. 您需要在目标的 Signing & Capabilities 的“Background Modes”中激活“Background fetch”
    2. 这发生在我身上,因为我需要再次登录 iCloud(我在“设置”中看到了提示,但如果你没有,请尝试退出并重新登录)

    【讨论】:

      猜你喜欢
      • 2020-01-01
      • 1970-01-01
      • 2021-07-30
      • 2020-03-19
      • 2017-01-02
      • 1970-01-01
      • 1970-01-01
      • 2014-10-24
      • 1970-01-01
      相关资源
      最近更新 更多