Как перебрать каждый ключ, который содержит текущий идентификатор райдера? - PullRequest
0 голосов
/ 27 января 2019

Я пытаюсь извлечь данные из firebase для размещения в текстовых представлениях, но код, который я имею, дает мне только один экземпляр всех ключей в «истории».

Я хочу получить данные, если «райдер» равен текущему идентификатору райдера.

Я пробовал разные решения здесь и в Интернете, но, похоже, ничто не помогало мне.

База данных 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 голосов
/ 28 января 2019

С помощью @Ratul Sharker моя проблема решена.Вот что мы должны были сделать - передать ключ из History в HistoryDetails.

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...