Mof*_*waw 5 core-data swift cloudkit
我目前正在制作一个应用程序,需要它的 CoreData 存储通过 iCloud 跨设备同步。
一切正常,只是不是实时同步。(或者至少有点接近)。当 Device1 更改某些内容后我在 Device2 上什么都不做时,它根本不同步。事实上,我必须最小化并重新打开 Device2 上的应用程序才能使同步正常工作。
这很好地证明了这一点:(来源)
这是我的代码片段:
let container: NSPersistentCloudKitContainer
var context: NSManagedObjectContext { container.viewContext }
init() {
container = NSPersistentCloudKitContainer(name: "__Decision")
guard let description = container.persistentStoreDescriptions.first else { ... }
description.setOption(true as NSObject, forKey:
NSPersistentStoreRemoteChangeNotificationPostOptionKey)
container.loadPersistentStores(completionHandler: { ... })
container.viewContext.automaticallyMergesChangesFromParent = true
container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
NotificationCenter.default.addObserver(self, selector: #selector(self.processUpdate), name: .NSPersistentStoreRemoteChange, object: nil)
}
@objc func processUpdate(notification: NSNotification) {
operationQueue.addOperation {
DispatchQueue.main.async { ... } //Fetch new synched data and update UI
}
}
lazy var operationQueue: OperationQueue = {
var queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
return queue
}()
Run Code Online (Sandbox Code Playgroud)
我遵循了苹果的文档和其他教程,因为这是我使用 CloudKit + CoreData 的第一个项目。
一切似乎都与他们所做的相同......我不知道并且几天以来一直在研究这个问题。
谢谢你!
我只是向您展示我的设置,因为我曾经遇到过同样的问题。我也使用 CloudKit 进行 macOS 和 iOS 同步,现在它可以工作了。使用 SwiftUI 更新视图。
在我的 AppDelegate 中,我首先注册 RemoteNotification
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
application.registerForRemoteNotifications()
return true
}
Run Code Online (Sandbox Code Playgroud)
我的 persistenContainer 看起来确实像你的:
lazy var persistentContainer: NSPersistentCloudKitContainer = {
let container = NSPersistentCloudKitContainer(name: "name")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
container.viewContext.automaticallyMergesChangesFromParent = true
container.viewContext.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy
return container
}()
Run Code Online (Sandbox Code Playgroud)
然后我的签名选项卡,添加背景模式:
..并添加 Push 和 iCloud
另外,要有耐心。有时同步确实需要几分钟才能更新。
| 归档时间: |
|
| 查看次数: |
885 次 |
| 最近记录: |