使用Swift中的Firebase查询最新条目

时间:2017-01-20 13:44:53

标签: swift firebase firebase-realtime-database

我是使用Firebase的新手,我无法找到如何做听起来非常简单的事情:列出我数据库的所有最新条目。

以下是我的数据库的截图:

database

所以,我试图列出最新的条目:

    // picturesRef = FIRDatabase.database().reference().child("pictures")
    let _ = self.picturesRef.queryOrdered(byChild: "createdTime").queryLimited(toLast: 50).observe(.value, with: { snapshot in
        // Stocking the result into picturesArr array
        for elem in picturesArr {
            print(elem.createdTime)
        }
    })

现在,当我显示每个项目的createdTime值时,我有类似的内容:

  • 1484738582.0
  • 1484000086.0
  • 1484738279.0
  • 1484734358.0
  • 1484625525.0
  • 1484728677.0

似乎没有从最旧的条目到最新的条目进行排序......

另外,当我更换" createdTime"在" fieldThatDoesntExist"的查询中,我得到完全相同的结果。

任何人都知道我在代码中哪里做错了什么?提前谢谢!

2 个答案:

答案 0 :(得分:1)

查询以正确的顺序返回项目。但是很有可能(相关代码似乎在您的问题中丢失)当您将快照转换为字典(根据定义无序)时,您将丢失该顺序。

为了使项目保持正确的顺序,请迭代snapshot.children

let picturesRef = FIRDatabase.database().reference().child("pictures")
let _ = picturesRef
  .queryOrdered(byChild: "createdTime")
  .queryLimited(toLast: 50)
  .observe(.value, with: { snapshot in
      for child in snapshot.children {
          print(child.key)
          print(child.child("createdTime").value
      }        
})

另见:

答案 1 :(得分:0)

Actualy,在使用以下内容对查询返回的数组进行排序后:

picturesArr.sort(by: {$0.createdTime > $1.createdTime})

我已经发现查询会返回我正在查找但未排序的条目。

对我来说看起来有点奇怪,也许有人知道为什么甚至更好,如何将结果排序?