Search code examples
iosswifticloudcloudkit

Child records not showing in the Shared Database when sharing the Parent record in CloudKit


I have an app where I can share records with other users, everything works when I share a single record, my issue is when I share a record (parent record) which has children records referencing it, I can see the parent record in the Shared Database in the CloudKit Dashboard after the user accepts the share but I don't see any of the related child records.

Based on the WWDC videos and some other threads here at Stack Overflow, the child records are automatically shared when you share the parent record, but it's not what I'm seeing, again, I can see the parent record in the Shared Database but no child records.

Here is an overview of how the app is set up in the CloudKit Dashboard.

In the CloudKit Dashboard, I have a Lists and an Items record type, where the Lists record is the parent of one or many Items. In the Items schema, I have a Reference field type which keeps a reference to its parent list.

Here is the code I'm using to save the parent record.

func shareList(){        
    let share = CKShare(rootRecord: self.list)

    if let listName = self.list.object(forKey: "name") as? String {
        self.listName = self.list.object(forKey: "name") as? String
        share[CKShare.SystemFieldKey.title] = "Sharing \(listName)" as CKRecordValue?

    } else {
        share[CKShare.SystemFieldKey.title] = "" as CKRecordValue?
    }
    share[CKShare.SystemFieldKey.shareType] = "com.mySite.lists" as CKRecordValue

    let sharingViewController = UICloudSharingController(preparationHandler: {(UICloudSharingController, handler: @escaping (CKShare?, CKContainer?, Error?) -> Void) in
        let modRecordsList = CKModifyRecordsOperation(recordsToSave: [self.list, share], recordIDsToDelete: nil)

        modRecordsList.modifyRecordsCompletionBlock = {
            (record, recordID, error) in

            handler(share, CKContainer.default(), error)
        }
        CKContainer.default().privateCloudDatabase.add(modRecordsList)
    })

     sharingViewController.delegate = self
     sharingViewController.availablePermissions = [.allowPrivate]
     self.navigationController?.present(sharingViewController, animated:true, completion:nil)
}

What I'm I missing? Is there any additional set up I need to do when sharing the parent record?

I'm right saying that the child records should automatically be shared alone with the parent record?

Here is a picture that demonstrates the relationship between the items and the list is working in the Private Database.

enter image description here


Solution

  • You have to set the parent on each child record using setParent: https://developer.apple.com/documentation/cloudkit/ckrecord/1690507-setparent

    Like this:

    childRecord.setParent(parentRecord)
    

    I hope that helps.