如何解决快速将 CloudKit 的结果附加到数组中
我将联系人变量声明为空字符串数组
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
我在其他函数中使用了变量contact
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,completion: nil)
return
}
}
解决方法
很难确定发生了什么,因为您忽略了 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)
}
}
}
作为旁注,我建议对所有查询 (MessageBox) 使用 CKQueryOperation
。这是管理来自 CloudKit 的数据流的一种更简洁的方式。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。