CloudKit CKReference List

2.7k views Asked by At

So I hava record that contains a field which is an CKReference List.

Now I would like to fetch all referenced(by this list of CKReferences) records(from another type) in batch.

Any Ideas?

1

There are 1 answers

2
William T. On BEST ANSWER

Let's say you have a record "Company" and they have a CKReference List field named "Employees".

Doing the fetch for the Company is easy but once you have the companyRecord, you now want to fetch its Employees. You can do it like this:

//first you need to create an array of employee record IDs
var employeeRecordIds = [CKRecordID]()
for employeeReference in companyRecord["Employees"] as! [CKReference] {
    employeeRecordIds.append(employeeReference.recordID)
}
//now you can fetch those employees
var fetchOperation = CKFetchRecordsOperation(recordIDs: employeeRecordIds)
fetchOperation.fetchRecordsCompletionBlock = {
    records, error in
    if error != nil {
        print("\(error!)")
    } else {
        for (recordId, record) in records {
            print("\(record)")
        }
    }
}
CKContainer.defaultContainer().publicCloudDatabase.addOperation(fetchOperation)