Setting up CloudKit with Core Data
This is something I keep forgetting how to do so I’m posting this as a reference for future me and anyone else that finds it helpful.
These instructions assume you have created a new Xcode project with these options.
- Language: Swift
- User Interface: SwiftUI
- Check the box for “Use Core Data”
- Check the box for “Use CloudKit
This will create some boiler plate Core Data code in the AppDelegate and SceneDelegate.
In the SceneDelete, add this line after creating the context
.
context.automaticallyMergesChangesFromParent = true
In Project Settings, select the target and add some entitlements.
- iCloud – Add this entitlement and select the “CloudKit” checkbox. Use the default container for your project or select one from the list if you have already created one.
- Background Modes – Add this entitlement and select the checkbox for “Remote notifications
That’s it really. From here you can start to work with SwiftUI views by adding the context into the environment for the initial view.
let contentView = ContentView().environment(\.managedObjectContext, context)