How to properly use queryOrderedByValue

后端 未结 2 606
挽巷
挽巷 2020-12-12 00:34

I have this function written in Swift that fetch the leaderboard and then shows it to the user :

@IBAction func onShowLeaderboardTapped(_ sender: Any) {
             


        
相关标签:
2条回答
  • 2020-12-12 01:16

    Change the structure

    scores
      -YUijia099sma
        name: "Ben"
        score: 9
      -Yij9a9jsffffd
        name: "Dimitar"
        score: 7
    

    then

    @IBAction func onShowLeaderboardTapped(_ sender: Any) {
            let leaderboardDB = FIRDatabase.database().reference().child("scores")
                               .queryOrdered(byChild: "score")
                               .queryLimited(toLast: 5)
    
            leaderboardDB.observeSingleEvent(of: .value, with: { (snapshot) in
                print("leaderboard snapshot:" ,snapshot)
            }, withCancel: nil)
    
        }
    

    *typing on my iPad so it's not tested and the syntax may not be perfect

    0 讨论(0)
  • 2020-12-12 01:19

    When you fire a query against Firebase, it returns the keys of the items that match your query, the value of those items and the relative order of the items in the result. If you listen for a .Value event, all three of these are combined into a single FIRDataSnapshot.

    But when you then either ask for the value property of that snapshot or print that snapshot as one block, the data is converted into a Dictionary. Since a dictionary can only contain keys and values, the ordering of the items is lost at that point. And as it turns out, the dictionary then prints the items ordered by their key.

    To get the items in order, you should iterate over them using snapshot.children:

    leaderboardDB.observeSingleEvent(of: .value, with: { (snapshot) in
        for child in snapshot.children {
            print(child.key)
        }
    }, withCancel: nil)
    

    Also see:

    • Firebase snapshot.key not returning actual key?
    • Firebase getting data in order
    • Firebase queryOrderedByChild() method not giving sorted data
    0 讨论(0)
提交回复
热议问题