问题更新CKRecord

时间:2016-05-31 17:01:31

标签: ios swift cloudkit ckrecord

我无法保存已保存的记录。 recordToSave是从服务器下载的CKRecord。是否可以更新它?

recordTosave.setValue("cat", forKey: "animal")

let publicData = CKContainer.defaultContainer().publicCloudDatabase

publicData.saveRecord(recordToSave, completionHandler:{(record: CKRecord?, error: NSError?) in
    if error == nil{  

    }else{
        print(error.debugDescription)
    }
})

1 个答案:

答案 0 :(得分:4)

您无法插入已存在于cloudkit中的记录。您可以使用CKModifyRecordsOperation修改记录。使用记录ID获取记录,然后通过修改操作进行更新。

let recordIDToSave = CKRecordID(recordName: "recordID")
let publicData = CKContainer.defaultContainer().publicCloudDatabase

publicData.fetchRecordWithID(recordIDToSave) { (record, error) in

    if let recordToSave =  record {

        //Modify the record value here
        recordToSave.setObject("value", forKey: "key")

        let modifyRecords = CKModifyRecordsOperation(recordsToSave:[recordToSave], recordIDsToDelete: nil)
        modifyRecords.savePolicy = CKRecordSavePolicy.AllKeys
        modifyRecords.qualityOfService = NSQualityOfService.UserInitiated
        modifyRecords.modifyRecordsCompletionBlock = { savedRecords, deletedRecordIDs, error in
            if error == nil {
                print("Modified")
            }else {
                print(error)
            }
        }
        publicData.addOperation(modifyRecords)
    }else{
        print(error.debugDescription)
    }
}