如何遍历包含当前骑手ID的每个键?

时间:2019-01-27 02:19:23

标签: ios swift firebase-realtime-database

我正在尝试从Firebase检索数据以放置在文本视图中,但是我所拥有的代码只给了我“历史记录”中所有键的一个实例。

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

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

Firebase数据库:

firebase database

我拥有的代码:

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
            }
        })

    }

1 个答案:

答案 0 :(得分:1)

在@Ratul Sharker的帮助下,我的问题已解决。这就是我们要做的-将密钥从“历史记录”传递到“ HistoryDe​​tails”。

TripHistory

在上一个屏幕中,该屏幕包含指向该页面的表格视图

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
    }
}

在TripDetail中

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

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