jazzedge
11/29/2017 - 5:23 PM

Swift - CloudKit - Fetch Add Save Delete multiple records

If you have necessity to manage many record at the same time you can create a CKModifyRecordsOperation, which allows you to add/save/delete all records at once.

01. Save and Delete Records at the same time

let recordsToSave: [CKRecord] ...
let recordIDsToDelete: [CKRecordID] ...
let saveRecordsOperation = CKModifyRecordsOperation(
      recordsToSave: recordsToSave,
      recordIDsToDelete: recordIDsToDelete
)
saveRecordsOperation.modifyRecordsCompletionBlock = { savedRecords, deletedRecordIDs, error in
    // handle errors here
}
let privateDB = CKContainer.defaultContainer().privateCloudDatabase
privateDB.addOperation(saveRecordsOperation)

02. Fetch and Update Records

var publicDatabase: CKDatabase? = CKContainer.default().publicCloudDatabase
var artworkRecordID = CKRecordID(recordName: "115")
publicDatabase?.fetch(withRecordID: artworkRecordID, completionHandler: {(_ artworkRecord: CKRecord, _ error: Error?) -> Void in
    if error != nil {
        // Error handling for failed fetch from public database
    }
    else {
            // Modify the record and save it to the database
        var date = artworkRecord["date"] as? Date
        artworkRecord["date"] = (date.addingTimeInterval(30.0 * 60.0)) as? CKRecord ?? CKRecord()
        publicDatabase?.save(artworkRecord, completionHandler: {(_ savedRecord: CKRecord, _ saveError: Error?) -> Void in
            // Error handling for failed save to public database
        })
    }
})