如何更新 CloudKit 中记录类型上的字段?
Posted
技术标签:
【中文标题】如何更新 CloudKit 中记录类型上的字段?【英文标题】:How to update a field on a Record Type in CloudKit? 【发布时间】:2016-07-20 19:17:08 【问题描述】:我正在尝试更新 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)
快速解释:首先我要获取长者的电话号码(每个长者都有不同的电话)并检查此电话号码是否在云端。如果是,则更新此长者的 careTakerId,具体来说!
在这里你可以看到正在创建这个“No Name”记录,上面的记录保持不变
有什么想法吗?
【问题讨论】:
哦,别介意语法,我使用的是 xcode 8 beta 2 【参考方案1】:做最简单的方法,获取记录、更新和保存:
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)
【讨论】:
谢谢,很有用。【参考方案2】:现在才意识到问题出在哪里:
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)
我真的是在创造一个新纪录!我只需要访问 results 变量,即 CKRecord 的向量,然后更改并保存字段!
【讨论】:
以上是关于如何更新 CloudKit 中记录类型上的字段?的主要内容,如果未能解决你的问题,请参考以下文章