我正在尝试更新CloudKit中的现有记录,但我正在创建一个新记录,而不是更改值!这是代码:
func pairing(phone: String, ctid: String) {
ctUsers = [CKRecord]()
print("THE PHONE IS: \(phone)\n")
let publicData = CKContainer.default().publicCloudDatabase
let predicate = Predicate(format: "phone == %@", phone)
let query = CKQuery(recordType: "Elder", predicate: predicate)
publicData.perform(query, inZoneWith: nil) { (results: [CKRecord]?, error: NSError?) -> Void in
if error != nil {
print(error?.localizedDescription)
}
if let users = results {
self.ctUsers = users
print("\nHow many users in cloud: \(self.ctUsers.count)\n")
if self.ctUsers.count != 0 {
let user = CKRecord(recordType: "Elder")
user["careTakerId"] = ctid
let publicData = CKContainer.default().publicCloudDatabase
publicData.save(user, completionHandler: { (record: CKRecord?, error: NSError?) in
if error == nil {
DispatchQueue.main.asynchronously(execute: { () -> Void in
print("CARETAKER updated successfully\n")
})
}
else {
print("\nHUEHUEHUEHUE\n")
print(error?.localizedDescription)
}
})
}
else {
print("\nELDER ISN'T IN CLOUD\n")
print(error?.localizedDescription)
}
}
}
}
快速解释:首先我得到了老人的电话号码(每个老人都有不同的电话)并检查这个电话号码是否在云端。如果是,那么更新THIS老人的 careTakerId 吧!
在这里你可以看到创建这个“No Name”记录并且上面的记录保持不变
有什么想法吗?
答案 0 :(得分:7)
以最简单的方式,获取记录,更新和保存:
let recordID = CKRecordID(recordName: "[record_name_here]")
database.fetch(withRecordID: recordID) { record, error in
if let record = record, error == nil {
//update your record here
self.database.save(record) { _, error in
completion?(error)
}
}
}
答案 1 :(得分:3)
现在才意识到问题出在哪里:
publicData.perform(query, inZoneWith: nil) { (results: [CKRecord]?, error: NSError?) -> Void in
if error != nil {
print(error?.localizedDescription)
}
if let users = results {
self.ctUsers = users
print("\nHow many users in cloud: \(self.ctUsers.count)\n")
if self.ctUsers.count != 0 {
let user = users.first //CKRecord(recordType: "Elder")
user?["careTakerId"] = ctid
let publicData = CKContainer.default().publicCloudDatabase
publicData.save(user, completionHandler: { (record: CKRecord?, error: NSError?) in
if error == nil {
DispatchQueue.main.asynchronously(execute: { () -> Void in
print("CARETAKER updated successfully\n")
})
}
else {
print("\nHUEHUEHUEHUE\n")
print(error?.localizedDescription)
}
})
}
else {
print("\nELDER ISN'T IN CLOUD\n")
print(error?.localizedDescription)
}
}
}
我真的在创造一个新纪录!我只需要访问结果变量,即CKRecord的向量,然后更改并保存该字段!