Syncing User Data and Preferences over iCloud, with Swift

It is a common user request… “I have an iPad and an iPhone, how can I save my favorites on one device and have them come up my other device?”

If users have to create an account to use your app, then this functionality can be built in to your backend. However, sometimes, we don’t want to force users to create accounts to use our apps. In that case, there is an easy solution that syncs user data across devices with only a few lines of code. It is iCloud Key-Value Storage. Working exactly like a local dictionary, it is unique for each iCloud user, and automatically syncs across each device belonging to that user.

If you use userDefaults to store user data, you’re already half-way there. iCloud Key-Value Storage works in a very similar way, with the added benefit that data survives app deletion.

Practical Example

Let’s say a user with two devices downloads your app, they’ve entered their birthdate into one and saved it. You want to store this data to iCloud Key-Value Storage so that when they open up your app on their other device, the birthdate will automatically be there already. Here’s what to do…

Activate the iCloud capability

Select your project target in Xcode and open the “Capabilities” section. Activate iCloud and ensure “Key-Value storage” is checked.

Activate the iCloud capability

4 Lines of Code

First, create a keyValueStore. You can create as many of these as you want, each is effectively a different dictionary. I usually create a global instance which can then be called from any class.

var keyStore = NSUbiquitousKeyValueStore()

Add data to your keyStore

keyStore.set("03/04/1989", forKey: "userBirthdate")

Retrieve the data on a new instance of your app

if let storedUserBirthdate = keyStore.string(forKey: "userBirthdate") {
  //Use retrieved birthdate
} else {
  //Ask user for birthdate
}

Thus far, the keyStore acts exactly like UserDefaults, i.e. data will only be stored locally. In order to allow all of the iCloud user’s devices to access the data, you need to sync by calling:

keyStore.synchronize()

It really is that simple.

One thing to keep in mind is that the syncs don’t necessarily happen immediately. As Apple’s Docs put it: the syncs happen “an appropriate later time”. iCloud Key-Value Storage is designed to sync data that doesn’t require constant and super-fast updating. Things like user settings & preferences.