How to find out if the "NSUbiquitousKeyValueStore.default.set" result was successful

408 views Asked by At

I am writing data from my application to iCloud as follows. How to determine whether this process was successful?

NSUbiquitousKeyValueStore.default.set("data", forKey: "key")  
NSUbiquitousKeyValueStore.default.synchronize()

Reference: https://developer.apple.com/documentation/foundation/nsubiquitouskeyvaluestore

1

There are 1 answers

1
infinitehz On

You should be able to get the value after setting it to see if it was set correctly.

I think it is important to note that your data is actually a string so you would use the string() function of NSUbiquitousKeyValueStore.default to get the value. The function required to get the stored value will change depending on the value's variable type.

// Set value
let data: String = "data"
NSUbiquitousKeyValueStore.default.set(data, forKey: "key")  
NSUbiquitousKeyValueStore.default.synchronize()

// Try to get value
if let dataString = NSUbiquitousKeyValueStore.default.string(forKey: "key") {
    if dataString == data {
        // The data stored correctly
    } else {
        // Handle condition if data is not stored
    }
}