首页 > 解决方案 > 将 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
}

}

标签: arraysswiftcloudkit

解决方案


很难确定发生了什么,因为您忽略了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 流出的数据的一种更简洁的方式。


推荐阅读