When new data is available on the CloudKit server, it sends a notification to all subscribed apps. A great way to handle these notifications is to add a method to CloudStore that should be called when there are new changes in the CloudKit database. Add the following extension to CloudStore.swift:
extension CloudStore { func handleNotification(_ dict: [String: AnyObject], completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { let notification = CKNotification(fromRemoteNotificationDictionary: dict) if notification.subscriptionID == "private-changes" { fetchDatabaseChanges { error in if error == nil { completionHandler(.newData) } else { completionHandler(.failed) } } } } }
This method takes a dictionary and a completion-handler as its arguments. Note that the completion-handler has one argument, which is UIBackgroundFetchResult. As mentioned before, CloudKit sends a silent push notification when data has changed to trigger a process that's very similar to background fetch.
The previous method uses the notification dictionary to create a CKNotification instance and then checks whether the notification originated through the subscription for the private database. If this is the case, the changes should be fetched and ultimately get persisted to the local database.
When you subscribe to database changes, CloudKit will notify your app when any data in the database changes. When you fetch database changes, CloudKit will not tell you what records have changed straight away. Instead, CloudKit will send you the database zones that have changed. A flexible CloudKit setup should be able to handle incoming data from different zones, which means that you might add a new zone to your database and the app should be able to handle this.
If your app receives a notification to inform it of new changes, CloudKit won't provide any additional information. Instead, it is your job to ask CloudKit for the relevant changes. Remember that you were able to request only data that has changed since a specific moment in the CloudKit dashboard? The same mechanism is used when you fetch changes for your app.