Search code examples
icloudnsubiquitouskeyvaluestore

NSUbiquitousKeyValueStore Notification for Current Device


I am using NSUbiquitousKeyValueStore to store user preferences in iCloud. To ensure that I understand how NSUbiquitousKeyValueStore works, I successfully stored a String value and monitored the value on a separate device. The following explains my configuration.

I started by observing the Notification that is posted when the NSUbiquitousKeyValueStore changes externally:

NSUbiquitousKeyValueStore.didChangeExternallyNotification

Then, I set a String value that was input of a UITextField:

let store = NSUbiquitousKeyValueStore.default
store.set(text, forKey: key)
store.synchronize()

To ensure that this works, I created a UIAlertController in the method that responds to the notification. I observed the alert appear on the secondary device within six seconds of setting the value on the primary device. However, I never observed the alert appear on the primary device after setting the value.

After reading the documentation for NSUbiquitousKeyValueStore, I was unable to find a reason that the primary device would not also receive the notification after updating the NSUbiquitousKeyValueStore.

Do I need a solution to save the updated values locally before setting them in the NSUbiquitousKeyValueStore? I can persist the values locally in UserDefaults before persisting them in NSUbiquitousKeyValueStore. However, it would require me to revert the values in UserDefaults if an error should occur during the attempt to persist them in the NSUbiquitousKeyValueStore. Without the primary device being notified of the changes that are persisted from it, will I even be notified of the error in the observation of the notification? I struggle to believe that I will if I am not receiving notifications when successful.

Is there something that I am missing, or is this the expected behavior?


Solution

  • Perhaps they updated the documentation (+ 1 yr since you asked).

    "This notification is sent only upon a change received from iCloud; it is not sent when your app sets a value."

    I assume that means that because no change is observed (the local device and iCloud are already in sync) - you don't get a notification.