I'm trying to update a existing Record in CloudKit but I'm creating a new Record instead of changing the value! Here it is the code:
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)
}
}
}
}
Quick explanation: First I'm getting the elder's phone number (every elder has a different phone) and check if this phone number is in cloud. If it is, then updates the careTakerId of THIS elder, specifically!
Here you can see that is creating this "No Name" record and the record above remains unchanged
Any ideas?
Only realized now where is the problem:
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)
}
}
}
I was literally creating a new record! I only needed to access the results variable, that is a vector of CKRecord and then change and save the field!