Specify Parent using NSPersistentCloudKitContainer

I am using NSPersistentCloudKitContainer in my app to sync from Core Data, but I need to allow the user to share my root model object. I want them to access all of it's children, and from what I understand, it requires that all child CKRecords have the root object set as thier parent. Since this framework generates the corresponding CKRecords behind the scenes, is there not a way to speicify this relationship?

Post not yet marked as solved Up vote post of Down vote post of
1.1k views

Replies

I need the same answer.
As of iOS 14, NSPersistentCloudKitContainer only supports the private database and the public database. If you want your users to be able to share data with others, you need to implement that code manually.

Here's a great explanation of how sharing works along with some sample code: https://developer.apple.com/documentation/cloudkit/sharing_cloudkit_data_with_other_icloud_users

If you want to share a certain object, you can ask NSPersistentCloudKitContainer for the underlying record using https://developer.apple.com/documentation/coredata/nspersistentcloudkitcontainer/3141668-record. Initialize a new CKShare and set the record as its root record. Retrieve all other records for the hierarchy you'd like to share and set their parent property to the root record (not the share). Then you can save the CKShare using CKModifyRecordsOperation. Please refer to the documentation I've mentioned above to set up a CKDatabaseSubscription and fetch changes from the shared database as. they come in.

FYI for anyone that comes across this, you set the parent record by using .setParent