I watched last WWDC 2016 What\'s New with CloudKit to understand how to share records with other users using CKShare
Single record sharing:
I believe Thunk's answer is incorrect, since you should not have to fetch any records with the parent reference to a given record. First, where would you search? The child records of the CKShare root record do not appear in your shared database and you don't have access to the other user's private zone. Luckily, CloudKit will push to you all child records referenced by the CKShare's root record. The following approach will also solve the second problem, you will be notified of any and all future changes automatically!
The key is to simply add a CKDatabaseSubscription
to the shared database in the CloudKit container. Let's assume you are the client. Anytime another user share's a record with you, the CKShare record and the underlying root record referenced by the share are both situated in a custom zone in that user's private database. When you accept the share (triggering an application delegate method userDidAcceptCloudKitShareWith
), the same CKShare and underlying record are now visible to you, except that they are both visible in your shared database. If you have subscribed to the shared database, the subscription will kick in and notify you right after you accept the share. Now you can fetch all changes in the shared database using CKFetchDatabaseChangesOperation
. In the recordZoneWithIDChangedBlock
, the CKRecordZoneID
of the sharing user's custom zone will be given. You use this to trigger a CKFetchRecordZoneChangesOperation
(be sure to perform this operation in the shared database!), which returns the CKShare, the underlying root record, and all records that have a parent reference to the underlying referenced record.
So with a simple database subscription you can automatically trigger and download all shares, root records, and children!
Regarding question 1, to find the records that have references to the parent, you'll need to create a query that checks the reference field for rootRecordID. This page from Apple has a section discussing retrieval options with code examples.
https://developer.apple.com/library/content/documentation/DataManagement/Conceptual/CloudKitQuickStart/AddingReferences/AddingReferences.html
Regarding question 2, you could constantly poll the server for updated records, but Apple discourages that in one of the WWDC videos since it generates a lot of network traffic (and thus burns through your monthly quota). I suggest adding a subscription notice on the CKshare. That way, you'll be notified when you need to fetch records.