检索存储在childByAutoID下的数据

时间:2017-09-16 11:05:49

标签: ios json swift database firebase

我的JSON树是:

"users" : {
  "3iQrxqczoGRQVMLUWVZu3MvJNyh1" : {
    "annotations" : {
      "-Ku99FZpxfy1sFu_rbTR" : {
        "BJ's Restaurant & Brewhouse" : {
          "annotationSubtitle" : "5699 Newark CA",
          "annotationTitle" : "BJ's Restaurant & Brewhouse",
        }
      },
      "-Ku9IbvW65305uwu7UuE" : {
        "Apple Infinite Loop" : {
          "annotationSubtitle" : "1 Cupertino CA",
          "annotationTitle" : "Apple Infinite Loop",

最初我已经能够使用此代码加载tableView。 for循环提取JSON树中的每个子节点,并将其附加到newAnnotations,然后将其放入AnnotationListItem,这是用于加载tableView的本地数组。 AnnotationListItem是我为保留annotationTitleannotationSubtitle等而制作的结构,我会在loadList中致电viewDidLoad。 :

func loadList() {
    if let uid = Auth.auth().currentUser?.uid {
        uidRef.child(uid).child("annotations").observeSingleEvent(of: .value, with: {snapshot in
            var newAnnotations: [AnnotationListItem] = []
            for item in snapshot.children {
                let annotationItem = AnnotationListItem(snapshot: item as! DataSnapshot)
                newAnnotations.append(annotationItem)
            }
            annotationList = newAnnotations
            self.tableView.reloadSections([0], with: .fade)
        })
    }
}

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return annotationList.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "listCell", for: indexPath)
    let annotatedItem = annotationList[indexPath.row]
    cell.textLabel?.text = annotatedItem.annotationTitle
    cell.detailTextLabel?.text = annotatedItem.annotationSubtitle
    return cell
}

现在我在添加新注释时创建了childAutoID,并在this example后创建了一个数组来存储childAutoID'

func someFunc() {
    guard let uid = Auth.auth().currentUser?.uid else { return }
    uidRef.child(uid).child("annotations").observe( .childAdded, with: { (snapshot) in

        var idKeys = [String]()  //this will hold your keys
        for snap in snapshot.children.allObjects {
            let id = snap as! DataSnapshot
            idKeys.append(String(id.key))
        }

        print(idKeys)
    })
}

正确打印了idKeys,但现在我无法将此数组集成到原始代码中。我无法再访问AnnotationListItem下的"annotations"子节点,因为我必须通过childByAutoID。我怎样才能做到这一点?如果它令人困惑,请告诉我,我会澄清。

0 个答案:

没有答案