访问 Firebase 数据库中的嵌套子项 Swift 3

Accessing Nested Children in Firebase Database Swift 3

我现在的firebase数据库结构是这样的

customer
  -L1x2AKUL_KNTKXyza
    name:"abc"
    subscription
      -L1x2AKlvmG0RXv4gL
        sub_no: "123"
        sub_name: ""
      -L1x2AKlvmG0RXv4ab
        sub_no: "456"
        sub_name" ""
  -L1x2AKUL_KNTKXymk
    name:"xyz"
    subscription
      -L1x2AKlvmG0RXv4xy
        sub_no: "789"
        sub_name: ""

我正在尝试一次访问所有客户记录的所有订阅。

这是我使用的代码:

var ref: DatabaseReference!

ref = Database.database().reference(withPath: "customer")

ref.observe(.value, with: { snapshot in
        let enumerator = snapshot.children

        while let rest = enumerator.nextObject() as? DataSnapshot {

            let imageSnap = rest.childSnapshot(forPath: "subscription")
            let dict = imageSnap.value as! NSDictionary

            //self.vehicleListDict.append(dict.object(forKey: "sub_no") as! NSDictionary)

            print("value : \(dict)")

        }
        print("vehicleListDict : \(self.vehicleListDict)")
    }) { (error) in
        print(error.localizedDescription)
    }

我无法一次访问所有客户记录中的所有订阅。它只能访问一级。我试图在存在的 while 中放置一个 while 循环,但这也没有给我所需的输出。相反,它进入无限循环。请任何人帮忙。我是第一次使用 firebase 实时数据库。

获取的值应该是

123
456
789

具体执行您所要求的代码是

let customerRef = self.ref.child("customer")
customerRef.observe(.childAdded, with: { snapshot in
    let subscriptionSnap = snapshot.childSnapshot(forPath: "subscription")
    for child in subscriptionSnap.children {
        let snap = child as! DataSnapshot
        let dict = snap.value as! [String: Any]
        let subNo = dict["sub_no"] as! String
        print(subNo)
    }
})

输出为

a123
a456
a789

*请注意,我将 sub_no 读作字符串,这就是我在前面添加 'a' 的原因。如果它们实际上是整数,则将行更改为

let subNo = dict["sub_no"] as! Integer

*note2 这会将 .childAdded 观察者留在有问题的主节点上,因此添加的任何其他子节点都会触发闭包中的代码。

编辑:

如果您只想一次检索所有数据而不留下 childAdded 观察者,那么这样做就可以了:

let customerRef = self.ref.child("customer")
customerRef.observeSingleEvent(of: .value, with: { snapshot in
    for customerChild in snapshot.children {
        let childSnap = customerChild as! DataSnapshot
        let subscriptionSnap = childSnap.childSnapshot(forPath: "subscription")
        for subscriptionChild in subscriptionSnap.children {
            let snap = subscriptionChild as! DataSnapshot
            let dict = snap.value as! [String: Any]
            let subNo = dict["sub_no"] as! String
            print(subNo)
        }   
    }
})

输出为

a123
a456
a789