TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

How to store UserDefaults options in iCloud

Swift version: 5.10

Paul Hudson    @twostraws   

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:

#import "MKiCloudSync.h"

Now open your AppDelegate.swift file, find the didFinishLaunchingWithOptions method, and add this line to it:

MKiCloudSync.start(withPrefix: "sync")

The "sync" part is important, because chances 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.

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

Sponsor Hacking with Swift and reach the world's largest Swift community!

Available from iOS 5.0

Similar solutions…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.1/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.