首页 > 解决方案 > 如何遍历包含当前骑手 id 的每个键?

问题描述

我正在尝试从 firebase 检索数据以放置在 textviews 中,但我拥有的代码只给了我“历史”中所有键的一个实例。

如果“骑手”等于当前骑手ID,我想获取数据。

我在这里和互联网上尝试了不同的解决方案,但似乎没有做我需要做的事情。

Firebase 数据库:

火力数据库

我的代码:

let rider = FIRAuth.auth()?.currentUser?.displayName

    // getting a reference to the node history
    historyRef = ref.child("history")

    // retrieve history key from firebase ....
    let query = historyRef.queryOrdered(byChild: "rider").queryEqual(toValue: uid)
    query.observe(.childAdded) { (snapshot) in

        // history auto generated key ............
        _ = snapshot.value as? String
        let key = snapshot.key

        // get values from history and place in outlet
        self.historyRef.child(key).observeSingleEvent(of: .value, with: { (snapshot) in

            if snapshot.exists() {

                var dict = snapshot.value as! [String: AnyObject]

                self.price = ((dict["ride_price"] as AnyObject) as! Double)
                self.txtPrice1.text = "\(self.price!)" // to make double work in textview
                self.txtPrice1.text = "\( Double(round(100 * self.price!)/100) )" // format .xx
                self.txtPrice2.text = "\( Double(round(100 * self.price!)/100) )"
                self.txtPrice3.text = "\( Double(round(100 * self.price!)/100) )"

                self.distance = ((dict["distance"] as AnyObject) as! Double)
                self.txtDistance.text = "\(self.distance!)"
                self.txtDistance.text = "\( Double(round(100 * self.distance!)/100) )"

                self.location = (dict["location"] as! String)
                self.txtLocation.text = self.location

                self.destination = (dict["destination"] as! String)
                self.txtDestination.text = self.destination

                self.timestamp = (dict["timestamp"] as! String)
                self.txtTimestamp.text = self.timestamp
            }
        })

    }

标签: iosswiftfirebase-realtime-database

解决方案


在@Ratul Sharker 的帮助下,我的问题得到了解决。这是我们必须做的——将密钥从 History 传递到 HistoryDe​​tails。

旅行历史

在我之前的屏幕中,包含指向相关页面的 tableview

private var selectedIndexPath: IndexPath?

// didSelectRowAt indexPath
selectedIndexPath = indexPath
performSegue(withIdentifier: "segueShowTripDetail", sender: self)

// add method:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    let key = completedTrips[selectedIndexPath!.row]
    if segue.identifier == "segueShowTripDetail" {
        let destination = segue.destination as! TripDetail
        destination.key = key
    }
}

在行程详情中

public var key: String! // container for the passed-in historyKey

// use passed-in 'key'
self.historyRef.child(self.key).observe(.value, with: { (snapshot) in

推荐阅读