如何正确使用 queryOrderedByValue [英] How to properly use queryOrderedByValue

查看:18
本文介绍了如何正确使用 queryOrderedByValue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 Swift 编写了这个函数来获取排行榜,然后将其显示给用户:

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

@IBAction func onShowLeaderboardTapped(_ sender: Any) {
        let leaderboardDB = FIRDatabase.database().reference().child("scores").queryOrderedByValue().queryLimited(toLast: 5)

        leaderboardDB.observeSingleEvent(of: .value, with: { (snapshot) in
            print("leaderboard snapshot:" ,snapshot)
        }, withCancel: nil)

    }

问题是当我获取它时,它给了我以下列表:

The problem is that when I fetch it, it gaves me the following list :

 Ben = 9;
 Gabriela = 12;
 Ivailo = 7;
 Petar = 10;
 Vania = 10;

它向我显示了前五名球员,但随后按字母顺序列出了他们.由于这不是一个大问题,我想知道是否有办法按值对它们进行排序.

It shows me the first five players, but then it lists them alphabetically. Since this is not a big problem I wonder if there is a way to order them by the value.

规则如下:

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null",
      "scores": {
      ".indexOn": ".value"
    }
  }
}

DB 的组织方式如下:

And the DB is organized as follows:

  matchrooms:
  users: 
  scores:
>      Ben: 9
>      Dimitar: 7
>      Gabriela: 12
>      Ishest: 6
>      Ivailo: 7
>      Ivan: 5
>      Marina: 3
>      Pesho: 3
>      Petar: 10
>      Rosen: 6
>      Vania: 10
>      Yasen: 2

那么,我的问题是如何正确使用 queryOrderedByValue() 来检索前五名球员并按他们的得分列出他们?

So, my question is how to properly use the queryOrderedByValue() to retrieve the first five players and list them by the points they've scored?

推荐答案

当您对 Firebase 发出查询时,它会返回与您的查询匹配的项的键、这些项的值以及项在其中的相对顺序结果.如果您侦听 .Value 事件,则所有这三个事件都会合并为一个 FIRDataSnapshot.

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.

但是,当您请求该快照的 value 属性将该快照打印为一个块时,数据将转换为字典.由于字典只能包含键和值,因此项目的顺序在此时丢失.事实证明,字典会打印出按关键字排序的项目.

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.

要按顺序排列项目,您应该使用 snapshot.children 遍历它们:

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)

另见:

这篇关于如何正确使用 queryOrderedByValue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆