Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 如何正确使用queryOrderedByValue_Swift_Firebase_Firebase Realtime Database - Fatal编程技术网

Swift 如何正确使用queryOrderedByValue

Swift 如何正确使用queryOrderedByValue,swift,firebase,firebase-realtime-database,Swift,Firebase,Firebase Realtime Database,我用Swift编写了此函数,用于获取排行榜,然后将其显示给用户: @IBAction func onShowLeaderboardTapped(_ sender: Any) { let leaderboardDB = FIRDatabase.database().reference().child("scores").queryOrderedByValue().queryLimited(toLast: 5) leaderboardDB.observeSingle

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

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

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

 Ben = 9;
 Gabriela = 12;
 Ivailo = 7;
 Petar = 10;
 Vania = 10;
它向我展示了前五名玩家,然后按字母顺序列出了他们。由于这不是一个大问题,我想知道是否有一种方法可以按价值排序

规则如下:

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null",
      "scores": {
      ".indexOn": ".value"
    }
  }
}
DB的组织结构如下:

  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()
检索前五名玩家,并根据他们的得分列出他们?

更改结构

scores
  -YUijia099sma
    name: "Ben"
    score: 9
  -Yij9a9jsddd
    name: "Dimitar"
    score: 7
然后


*在我的iPad上键入,这样它就不会被测试,语法也可能不完美

当您对Firebase发起查询时,它会返回与您的查询匹配的项目的键、这些项目的值以及结果中项目的相对顺序。如果您侦听.Value事件,则这三个事件将合并到一个FIRDataSnapshot中

但是,当您随后请求该快照的
属性或将该快照打印为一个块时,数据将转换为字典。由于字典只能包含键和值,因此此时项的顺序将丢失。结果是,字典会打印出按键排序的项目

要按顺序获取项目,应使用快照对其进行迭代。子项:

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


首先,这是构建firebase数据的一种不好的方法,您应该有一个由childByAutoId生成的节点名,子节点名为:some name和score:some score。然后你可以查询这些节点并按名称或分数等进行排序。实际上,你是按值排序的,这正是你得到的-B)en,G)abriela,I)valio(B,G,I,pv)。我知道这是一种不好的方式,如果你注意到的话,我有一个用户节点,他们在那里注册了childByAutoId函数。我生成的列表只是为了与firebase一起玩。谢谢,它帮助了我,我必须使用snap.value。现在我尝试了“snap.children”,效果很好。在同一查询中,snap.value返回未排序的数据snap.children返回已排序的数据
leaderboardDB.observeSingleEvent(of: .value, with: { (snapshot) in
    for child in snapshot.children {
        print(child.key)
    }
}, withCancel: nil)