我正在努力解决以下问题。尽管进行了深入的搜索,但我还没有成功。
我的开发环境是 macOS Big Sur Beta 下的 Xcode 12.0 beta (但是,问题在 Catalina 下的 Xcode 11.5 上似乎相同)。我正在开发的应用程序是多平台的,包括 macOS 10.16 和 iOS 13.5 目标。该应用程序使用 NSPersistentCloudKitContainer 为 CoreData 配置。
虽然registerForRemoteNotifications()
在 iOS 目标中成功并没有任何问题,并且didRegisterForRemoteNotificationsWithDeviceToken
被正确调用,但在 macOS 目标中没有任何反应:既没有didRegisterForRemoteNotificationsWithDeviceToken
也没有didFailToRegisterForRemoteNotificationsWithError
被触发。显然,在 macOS 和 iOS 目标上都正确配置了 CloudKit 和 PushNotification 权利。也在 macOS 上查询isRegisteredForRemoteNotifications
返回...true
macOS 和 iOS 上的 persistentContainer 定义代码相同(NB 完全默认,并且automaticallyMergesChangesFromParent
已正确设置)
var persistentContainer: NSPersistentCloudKitContainer = {
let container = NSPersistentCloudKitContainer(name: "MyFinance")
guard let description = container.persistentStoreDescriptions.first else {
os_log("Failed to retrieve a persistent store description. Aborting application.", log: log, type: .error)
fatalError("###\(#function): Failed to retrieve a persistent store description.")
}
description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error {
guard let error = error as NSError? else { return }
os_log("Failed to load persistent store. Aborting application.", log: log, type: .error)
fatalError("###\(#function): Failed to load persistent stores:\(error)")
}
})
container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
container.viewContext.transactionAuthor = "xxx"
do {
try container.viewContext.setQueryGenerationFrom(.current)
} catch {
os_log("Failed to pin viewContext to the current generation. Aborting application.", log: log, type: .error)
fatalError("###\(#function): Failed to pin viewContext to the current generation:\(error)")
}
container.viewContext.automaticallyMergesChangesFromParent = true
return container
}()
最终结果是,虽然 CoreData 与推送通知的同步在 macOS -> iOS 方向上得到了正确处理,但在相反方向上没有任何反应(因为 macOS 上的推送通知没有被触发):从 iOS 到 macOS,CoreData 在 app 处重新对齐仅引导。
任何人都可以请自己朝着正确的方向前进吗?我从两天开始就用头撞墙,没有任何明智的结果......
PS 在运行 macOS 目标时还有另一个“症状”:任何时候在应用程序中触发 API 调用,尽管调用成功,Xcode 调试控制台中仍会出现以下消息:
nw_resolver_start_query_timer_block_invoke [Cxx] Query fired: did not receive all answers in time for xxx (the API url)
iOS 目标不会发生这种情况。我无法为此找到一个体面的解释。我真的不知道这是否与推送通知问题有关。在公共领域搜索它并不快乐。