arrays - 将 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)")
我在其他功能中使用可变接触
函数发送SOS(){
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
}
}
解决方案
很难确定发生了什么,因为您忽略了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 流出的数据的一种更简洁的方式。
推荐阅读
- google-cloud-build - “gcloud builds submit”不会因为缺少所需的替换而触发错误
- windows - 使用 Robocopy /minage:最大天数是多少?
- swift - 更改内容顺序时,SwiftUI MacOS 列表布局出现故障
- javascript - Angular Material 选项 - 硬编码值有效,动态返回值无效
- android - Android应用程序图标点击需要太多时间才能打开
- javascript - 我的 Angular 11 cli 应用程序无法与 jest 一起使用。我得到的错误:TypeError:无法读取未定义的属性“路径”
- ios - 如何将数据发布到 CKRecord Fields objc
- ios - 检查自动续订订阅是否仍然有效?斯威夫特 5
- c++ - 如何在课堂上模板化 2D 容器?
- jquery - 为什么角度数据表不呈现?