Firebase多级数据库进入tableview

时间:2017-03-09 21:18:30

标签: ios firebase swift3 firebase-realtime-database

如何将孩子的数据深入到名称未知的数据库中?

我的示例结构如下。

enter image description here

此代码有效(获取快照数据),但我正在硬编码第二个孩子。我不会总是知道这个值(总线1 )。

    let ref = FIRDatabase.database().reference()
    let usersRef = ref.child("Trips").child("Bus 1")
    usersRef.observeSingleEvent(of: .value, with: { (snapshot) in

        for snap in snapshot.children {
            let userSnap = snap as! FIRDataSnapshot
            let uid = userSnap.key //the uid of each user
            let userDict = userSnap.value as! [String:AnyObject] //child data
            let personOn = userDict["getOn"] as! String
            print("key = \(uid) is at getOn = \(personOn)")
        } 
    })

这将打印:

key = Stop 1 is at getOn = 3
key = Stop 2 is at getOn = 7

我应该以不同的方式构建这个吗?谄?

谢谢,让我知道任何问题。

这是一种更优选的方式,因为我有一个TripDetails类,它进入一个数组加载到表中。但同样,我不知道第二个孩子的名字是什么。

FIRDatabase.database().reference().child("Trips").child("Bus 1").observe(.childAdded, with: { (snapshot) in

        if let dictionary = snapshot.value as? [String: AnyObject] {
            let trip = TripDetails()

            trip.setValuesForKeys(dictionary)
            self.trips.append(trip)


            DispatchQueue.main.async {
                self.tableView.reloadData()
            }

        }
        print(snapshot)
    }, withCancel: nil)

1 个答案:

答案 0 :(得分:0)

我仍然不确定你想要什么数据。如果你想要的只是所有数据,你可以这样做。

let ref = FIRDatabase.database().reference().child("Trips")
ref.observeSingleEvent(of: .value, with: { snapshot in
    let enumerator = snapshot.children
    while let bus = enumerator.nextObject() as? FIRDataSnapshot {
        print("\(bus.key)")
        let enumerator = bus.children
        while let stop = enumerator.nextObject() as? FIRDataSnapshot {
            let stopDict = stop.value as? [String: Any]
            let uid = stop.key
            let personOn = stopDict?["getOn"] as? String
            print("key = \(uid) is at getOn = \(personOn)")
        }
    }
})