读取firebase上的数据

时间:2017-08-28 22:06:50

标签: swift firebase-realtime-database

这是我的数据结构。 enter image description here

这就是我加载俱乐部数据及其地址的方式。

func loadClubs() {

        ref = Database.database().reference()
        ref.child("club").observe(DataEventType.childAdded, with: { (clubSnapshot) in
            if let clubDict = clubSnapshot.value as? [String : AnyObject] {
                let name = clubDict["name"] as! String
                let explanation = clubDict["explanation"] as! String
                let courtNum = clubDict["courtNum"] as! Int
                let membershipFee = clubDict["membershipFee"] as! Int
                let visitorFee = clubDict["visitorFee"] as! Int
                let hasCarParking = clubDict["hasCarParking"] as! Bool
                let club2 = Club2(name: name, explanation: explanation, courtNum: courtNum, membershipFee: membershipFee, visitorFee: visitorFee, hasCarParking: hasCarParking)
                self.club2Array.append(club2) // Add to clubArray
                print(self.club2Array)
                self.tableView.reloadData()
            }
            let addressRef = Database.database().reference()
            addressRef.child("address").child(clubSnapshot.key).observe(DataEventType.childAdded, with: { (addressSnapshot) in
                if let addressDict = addressSnapshot.value as? [String: AnyObject] {

                    let clubAddress = ClubAddress(postCode: addressDict["postcode"] as! String, cityName: addressDict["city"] as! String, ward: addressDict["ward"] as! String, address1: addressDict["address1"] as! String, address2: addressDict["address2"] as! String)

                    self.addressArray.append(clubAddress)
                    print(self.addressArray)
                }
            })
        })
    }
基本上,在检索了俱乐部的每个快照后,我获得了俱乐部的密钥(-KsJB9TkoGNIkiZFGg7),然后使用该密钥来检索地址。 但是,print(self.addressArray)不会打印任何内容。 我在if let addressDict = addressSnapshot.value as? [String: AnyObject] {添加了一个调试断点,它不会停止调试过程。 为什么不打电话? 我在这里想念什么?

1 个答案:

答案 0 :(得分:3)

啊!你的代码非常接近。

请记住.childAdded会遍历所有子节点并加载每个子节点。

在您的情况下,您不希望迭代所有地址节点,只需要一个,并且不想离开观察者。

为此,我们通过observeSingleEvent(of .value)加载地址节点的特定节点子数据。这是重要部分的片段。

let addressRef = Database.database().reference()
addressRef.child("address").child(clubSnapshot.key)
          .observeSingleEvent(of: .value, with: { (addressSnapshot) in
    let dict = addressSnapshot.value as! [String: Any]
    let address = dict["address1"] as! String
    print(address)