Share an object managed by NSPersistentCloudKitContainer with other users

One question I often see on DevForums and in my day DTS job is if a Core Data object managed by NSPersistentCloudKitContainer can be shared with other iCloud users.
The answer is yes but you need to do it using CloudKit API directly because NSPersistentCloudKitContainer doesn’t support CloudKit shared database (CKContainer.sharedCloudDatabase) today.

Assuming you have a Core Data object, let’s say a document, that you’d like to collaborate with your colleagues:
  1. You are the document owner and can use NSPersistentCloudKitContainer to fully manages the document and synchronize it across your devices.

  2. You can grab a CloudKit record associated with your document from NSPersistentCloudKitContainer using record(for:) or recordID(for:), and share it to your colleagues using UICloudSharingController. See our Sharing CloudKit Data with Other iCloud Users sample for how to share a CloudKit record.

  3. After accepting the sharing, your colleague, as a participant, can view or edit the shared document. The document resides in the participant’s CloudKit shared database and you have to manage it with your own code.

  4. When your colleague edits and saves the shared document, the changes go to the owner’s private database, and eventually synchronize to NSPersistentCloudKitContainer on the owner side. 

As you can see, you need to implement #2 and #3 with your own code because NSPersistentCloudKitContainer can’t manage the data in the participant's shared database. If you have any difficulty after going through the above sample code, you can contact Apple’s DTS for help.

Replies

Hi thank you for making this post. This is really helpful. I have a follow up. There is a 5th point that is missing. What happens when the owner modifies something in the shared document. The other participant can't use private database auto synced with NSPersistentCloudKitContainer because they must use CKContainer.sharedCloudDatabase for shared documents. How to I manually fetch the changes in real time reliability? I saw Maintain a Local Cache For CloudKit Records described here https://developer.apple.com/documentation/cloudkit/sharing_cloudkit_data_with_other_icloud_users but do not understand it. Could you please describe in simpler steps to keep the CKContainer.sharedCloudDatabase synced in real time. Thank you 🙏
The owner’s changes on a shared document go to the participant’s sharedCloudDatabase, and the participant side can use CloudKit APIs to manage the changes. To get informed of the changes, for example, the participant side can create a CKDatabaseSubscription to subscribe the changes of its own sharedCloudDatabase. With that, when the owner makes changes on a shared document, a participant gets a CloudKit notification, and can then fetch the changes using CKFetchDatabaseChangesOperation. The sample mentioned above demonstrates all these details.