Swift version: 5.0
iOS has a built-in iCloud sync system called
NSUbiquitousKeyValueStore, but to be honest it's pretty unpleasant to work with. Fortunately, other developers have written simple wrappers around it so that you can forget about iCloud and focus on the interesting things instead – i.e., the rest of your app.
One such example is called MKiCloudSync and it's available from here. It's open source and so easy to use you literally don't notice that it's there once you've added it to your app – it just silently syncs your
UserDefaults values to and from iCloud.
To use it, go here and click Download Zip. Inside the zip file you'll find MKiCloudSync.h and MKiCloudSync.m, and you should drag them both into your Xcode project. Xcode will ask you if you want to create an Objective-C bridging header, and you should click "Create Bridging Header" - this is required because MKiCloudSync is written in Objective-C rather than Swift.
To actually use the library, open your new bridging header (it'll be called something like YourProject-Bridging-Header.h) and add this:
Now open your AppDelegate.swift file, find the
didFinishLaunchingWithOptions method, and add this line to it:
The "sync" part is important, because changes are you won't want to sync everything to iCloud. With that prefix, MKiCloudSync will copy to iCloud only
UserDefaults keys that start with
sync – you can now choose what you want to sync just by naming your keys appropriately.
There is one final, important thing to do: you need to enable iCloud for your app. This is done inside the Capabilities tab of your target's settings – find iCloud, then flick its switch to be On.
Available from iOS 5.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.