检索子节点数据

时间:2016-10-06 07:19:20

标签: ios swift firebase firebase-realtime-database

我正在尝试恢复特定子节点上的数据。结构如下:

RESTAURANTS
    KTNfWKLD0isCsrpys
        name: “McDonalds”
        loc: “LA”
    KTNfWKLD0isCsrpys
        name: “KFC”
        loc: “LV”

代码:

FIRDatabase.database().reference().child("RESTAURANTS".observeSingleEventOfType(.ChildAdded, withBlock: { (snapshot) in

        for names in snapshot.children {
            self.loadingNames.append(names.key)
        }

    })

我尝试了这个,但我只得到像[“name”,”loc"]这样的孩子名字,但我想得到像[“McDonalds”,”KFC”]这样的名字。

2 个答案:

答案 0 :(得分:1)

尝试这样的事情......

FIRDatabase.database().reference().child("RESTAURANTS".observeEventType(.ChildAdded, withBlock: { (snapshot) in

    if let name = snapshot.value?["name"] as? String {
        self.loadingNames.append(name)
    }
})

修改:将观察者observeSingleEventOfType更改为observeEventType

答案 1 :(得分:0)

您可以将名称附加到字符串数组中:

FIRDatabase.database().reference().child("RESTAURANTS".observeSingleEventOfType(.ChildAdded, withBlock: { (snapshot) in
  for names in snapshot.children {
    if let name = names as? FIRDataSnapshot  {
      let nameValue = name.childSnapshot(forPath: "name").value as! String
      self.loadingNames.append(nameValue)
    }
  }  
})