cloudkitckmodifyrecordsoperation

CloudKit - How to retrieve the ckRecordID of the record just saved using CKModifyRecordsOperation


I'm using CoreData for keeping a local cache of records in CloudKit. When saving a new record, I do the following:

  1. Insert record to CoreData. I flag this record as not updated in CloudKit. Just in case my CKModifyRecordsOperation fails, I can still update it at a later time to CloudKit using this flag.
  2. Insert record to CloudKit using CKModifyRecordsOperation.
  3. Try fetching the ckRecordID of the record inserted in step #2. (That's where my logic fails as I'm not sure how I can achieve this). I do not have any other keys (reference) and wish to use only CKRecordID as a reference between CoreData and CloudKit.
  4. Update the ckRecordID (fetched in step #3) to CoreData.

What would be the best logic to solve the above? Thank you for your time and responses.


Solution

  • I solved this by creating a CKRecordID locally and updating it in CloudKit. Below is the quote from apple documentation:

    To assign a custom record ID to a new record, you must create the CKRecordID object first. You need to know the intended name and zone information for that record, which might also require creating a CKRecordZone.ID object. After creating the record ID object, initialize your new record using its init(__recordType:recordID:) method.

    Here's my code:

    let zone = CKRecordZone(zoneName: Schema.Zone.group)
    let uuid = NSUUID()
    let recordType = Schema.RecordType.group
    let recordName = uuid.uuidString
    let recordID = CKRecordID(recordName: recordName, zoneID: zone.zoneID)
    let newRecord = CKRecord(recordType: recordType, recordID: recordID)