将 CloudKit 的结果快速追加到数组中
Posted
技术标签:
【中文标题】将 CloudKit 的结果快速追加到数组中【英文标题】:Append result of CloudKit into array in swift 【发布时间】:2021-01-12 13:46:18 【问题描述】:我将联系人变量声明为空字符串数组
var contact = [String] ()
然后我查询从CloudKit输出结果,当我访问控制器一次时,var contact成功添加了一个数组
let predicate = NSPredicate(value: true)
let query = CKQuery(recordType: "Note", predicate: predicate)
database.perform(query, inZoneWith: nil) (record, error) in
for record: CKRecord in record!
let name = record.value(forKeyPath: "content") as! String
print ("There is a note \"\(name)\"")
self.contact.append(name)
self.contact.append (name)
print ("There is a note \" \ (name) \ "")
但是第二次访问时,var联系人又变空了
print ("check all array append \ (contact)")
Succes append firstime access the controller
Failed append secondtime access the controller
我在其他功能中使用可变接触
func sendSOS()
if canSendText()
//compese message with google link
let googleLink = "https://www.google.com/maps/place/" + String(myLatitude!) + "+" + String(myLongtitude!)
let SMStext = "EMERGENCY!!, Tolong Bantu saya di lokasi Latitude: " + String(myLatitude!) + "\n Longtitude: " + String(myLongtitude!) + " " + googleLink
let messsageCompose = MFMessageComposeViewController()
messsageCompose.messageComposeDelegate = self
messsageCompose.recipients = contact;
messsageCompose.body = SMStext
present(messsageCompose, animated: true, completion: nil)
else
// create the alert
let alert = UIAlertController(title: "No SMS available.", message: "Please find a better location and try again!", preferredStyle: UIAlertController.Style.alert)
// add an action (button)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
return
【问题讨论】:
缺少更多上下文:联系人何时初始化?它是某种实例吗? ... 我在contactcontroller.swift中初始化了联系人,并在其他函数中使用 【参考方案1】:很难确定发生了什么,因为您忽略了 contact
数组相对于 CKQuery
的初始化方式。
database.perform
行看起来有点可疑。我很确定它会返回一个 CKRecords
数组,所以你应该有:
database.perform(query, inZoneWith: nil) records, error in
//records is an optional array
if let records = records
for record in records
//You might have to parse record.values to get its key/value pairs
let name = record["content"] as? String ?? "No Name"
print("There is a note: \(name)")
//:::
self.contact.append(name)
附带说明,我建议对所有查询使用CKQueryOperation
(docs)。这是管理从 CloudKit 流出的数据的一种更简洁的方式。
【讨论】:
以上是关于将 CloudKit 的结果快速追加到数组中的主要内容,如果未能解决你的问题,请参考以下文章
CloudKit 查询与 modifyDate 始终返回无结果