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

时间:2018-02-19 07:00:01

标签: ios swift firebase swift3 firebase-realtime-database

我当前的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循环,但这也没有给我所需的输出。它代之以无限循环。请任何人都可以帮忙。我是第一次使用firebase实时数据库。

获取的值应为

123
456
789

1 个答案:

答案 0 :(得分:3)

具体做你要求的代码是

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作为STRING阅读,这就是我在前面添加'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