Why is my iCloud KVS Observer not working

373 Views Asked by At

In my app I implemented a Preferences class that looks like this.

public class Preferences: Codable {
    public static var sharedPreferences: Preferences = {
        let preferences = Preferences()

        return preferences
    }()

    public class func shared() -> Preferences {
        return sharedPreferences
    }

    private let cloud: NSUbiquitousKeyValueStore = NSUbiquitousKeyValueStore.default

    public init () {
        NotificationCenter.default.addObserver(self, selector: #selector(keysDidChangeOnCloud(notification:)),
                                               name: NSUbiquitousKeyValueStore.didChangeExternallyNotification,
                                               object: nil)
        self.cloud.synchronize()
    }

    @objc func keysDidChangeOnCloud(notification: Notification) {
        print("CLOUD CHANGED")
    }
}

I observe a change in the Key Value storage. That print() is never executed though. Any idea why?

1

There are 1 best solutions below

1
Brian M On

I believe you need to observe the NSUbiquitousKeyValueStore.default object like so:

NotificationCenter.default.addObserver(self, selector: #selector(keysDidChangeOnCloud(notification:)),
                                           name: NSUbiquitousKeyValueStore.didChangeExternallyNotification,
                                           object: NSUbiquitousKeyValueStore.default)