Share Core Data between users with NSPersistentCloudKitContainer

3.7k views Asked by At

Apple introduced the NSPersistentCloudKitContainer with iOS 13 which enable us to use CloudKit with Core Data. I got it working pretty much instantly on different devices but my main issue is still left.

Is it possible to share the data in an easy way with other users? I've been reading on CKShare but don't see how I can go from NSPersistentCloudKitContainer to that in an easy way.

3

There are 3 answers

0
samwize On

As announced in WWDC 2021, you can now share to other iCloud users. https://developer.apple.com/videos/play/wwdc2021/10015/

2
orange On

There are methods on NSPersistentCloudKitContainer for accessing the underlying cloudkit records: https://developer.apple.com/documentation/coredata/nspersistentcloudkitcontainer. For example,

func record(for managedObjectID: NSManagedObjectID) -> CKRecord?

So in theory you could use this method to obtain a CKRecord then create a CKShare manually.

BUT as of the current beta release (beta 3) these methods seem to return nil. It seems like they wouldn't have included these methods if they wanted to keep the implementation hidden. So we're in this spot where you can implement the entire sync yourself and get sharing, or use their sync implementation but not get sharing. I hope the lack of implementation on these methods is simply an early beta issue.

12
Bas On

It seems this is now possible in iOS 14.0+ Beta and macOS 11.0+ Beta via the new databaseScope property: https://developer.apple.com/documentation/coredata/nspersistentcloudkitcontaineroptions/3580372-databasescope

The possible values are .public (the public database), .private (the private database) and .shared (the shared database).

E.g.:

let container = NSPersistentCloudKitContainer(name: "test")
guard let description = container.persistentStoreDescription.first else {
fatalError("Error")
}
description.cloudKitContainerOptions?.databaseScope = .shared

The video https://developer.apple.com/videos/play/wwdc2020/10650 describes how to sync the Core Data store with the CloudKit public database by setting the databaseScope value to .public.

[UPDATE] Unfortunately, it seems sharing is not (yet?) supported, even though the databaseScope = .shared property suggests otherwise. Please refer to https://developer.apple.com/forums/thread/649630?login=true&page=1#621748022 as pointed out by Brian M below.