LAST CHANCE: Save 50% on all my Swift books and bundles! >>

Syncing SwiftData with CloudKit

Paul Hudson    @twostraws   

SwiftData can sync all your user's data with iCloud, and best of all it often takes absolutely no code.

Before you start, there's an important warning: syncing data to iCloud requires an active Apple developer account. If you don't have one, the following will not work.

Still here? Okay, in order to sync data from local SwiftData storage up to iCloud, you need to enable the iCloud capability for your app. We haven't customized our app capabilities before, so this step is new.

First, click the "SwiftDataTest" app icon at the top of your project navigator. This should be directly above the SwiftDataTest group.

Second, select "SwiftDataTest" under the "TARGETS" list. You should see a bunch of tabs appear: General, Signing & Capabilities, Resource Tags, Info, and more. We want Signing & Capabilities, so please select that now.

Third, press "+ CAPABILITY" and select iCloud, which should make iCloud appear in the list of active capabilities – you'll see three services are possible, a "CloudKit Console" button, and more.

Fourth, check the box marked CloudKit, which is what allows our app to store SwiftData information in iCloud. You'll also need to press the + button to add a new CloudKit container, which configures where the data is actually stored in iCloud. You should use your app's bundle ID prefix with "iCloud." here, for example iCloud.com.hackingwithswift.swiftdatatest.

Fifth, press "+ CAPABILITY" again, then add the Background Modes capability. This has a whole bunch of configuration options, but you only need to check the "Remote Notifications" box – that allows the app to be notified when data changes in iCloud, so it can be synchronized locally.

And that's it – your app is all set to use iCloud for synchronizing SwiftData.

Perhaps.

You see, SwiftData with iCloud has a requirement that local SwiftData does not: all properties must be optional or have default values, and all relationship must be optional. The first of those is a small annoyance, but the second is a much bigger annoyance – it can be quite disruptive for your code.

However, they are requirements and not merely suggestions. So, in the case of Job we'd need to adjust its properties to this:

var name: String = "None"
var priority: Int = 1
var owner: User?

And for User, we'd need to use this:

var name: String = "Anonymous"
var city: String = "Unknown"
var joinDate: Date = Date.now
@Relationship(deleteRule: .cascade) var jobs: [Job]? = [Job]()

Important: If you don't make these changes, iCloud will simply not work. If you look through Xcode's log – and CloudKit loves to write to Xcode's log – and scroll near the very top, SwiftData should try to warn you when any properties have stopped iCloud syncing from working correctly.

Once you've adjusted your models, you now need to change any code to handle the optionality correctly. For example, adding jobs to a user might use optional chaining like this:

user1.jobs?.append(job1)
user1.jobs?.append(job2)

And reading the count of a user's jobs might use optional chaining and nil coalescing, like this:

Text(String(user.jobs?.count ?? 0))

I'm not a particularly big fan of scattering that kind of code everywhere around a project, so if I'm using jobs regularly I'd much rather create a read-only computed property called unwrappedJobs or similar – something that either returns jobs if it has a value, or an empty array otherwise, like this:

var unwrappedJobs: [Job] {
    jobs ?? []
}

It's a small thing, but it does help smooth over the rest of your code, and making it read-only prevents you trying to change a missing array by accident.

Important: Although the simulator is created at testing local SwiftData applications, it's pretty terrible at testing iCloud – you might find your data isn't synchronized correctly, quickly, or even at all. Please use a real device to avoid problems!

Hacking with Swift is sponsored by Essential Developer.

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until July 28th.

Click to save your free spot now

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

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.6/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.