How to listen to remote changes in CloudKit CoreData

Issue #783

Remove chane notification

Read Consuming Relevant Store Changes

If the import happens through a batch operation, the save to the store doesn’t generate an NSManagedObjectContextDidSave notification, and the view misses these relevant updates. Alternatively, the background context may save changes to the store that don’t affect the current view—for example, inserting, modifying, or deleting Shape objects. These changes do generate context save events, so your view context processes them even though it doesn’t need to.

Also, the doc mention NSPersistentStoreRemoteChangeNotificationOptionKey

1
2
3
4
5
6
7
8
9
10
11
let remoteChangeKey = "NSPersistentStoreRemoteChangeNotificationOptionKey"
description?.setOption(true as NSNumber,
forKey: remoteChangeKey)

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

In the app, the value of NSPersistentStoreRemoteChangeNotificationPostOptionKey is NSPersistentStoreRemoteChangeNotificationOptionKey

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let container = NSPersistentCloudKitContainer(name: name)

guard let description = container.persistentStoreDescriptions.first else {
assertionFailure()
return nil
}

description.setOption(
true as NSNumber,
forKey: NSPersistentHistoryTrackingKey
)

description.setOption(
true as NSNumber,
forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey
)

Updated at 2021-02-25 22:42:37

Comments