在Swift中使用Firebase查询最新条目 [英] Query latest entries using Firebase in Swift

查看:55
本文介绍了在Swift中使用Firebase查询最新条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Firebase的新手,我找不到如何做听起来很简单的事情:列出数据库中的所有最新条目.

I'm new using Firebase and I can't find how to do what sounds really simple to do : list all the latest entries of my database.

这是我的数据库的屏幕截图:

Here is a screenshot of what my database looks like :

因此,我正在尝试列出类似这样的最新条目:

So, I'm trying to list the latest entries like that :

    // 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值时,我会看到类似这样的内容:

And right now, when I'm displaying the createdTime value of each item, I have something like :

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

从最早的条目到最新的条目似乎没有什么顺序...

Which doesn't seem to be ordered from the oldest entry to the newest one...

此外,当我用"fieldThatDoesntExist"替换查询中的"createdTime"时,我得到的结果完全相同.

Also, when I replace "createdTime" in the query by "fieldThatDoesntExist", I have the exact same result.

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

Anyone would know where did I do something wrong in the code ? Thanks in advance !

推荐答案

查询以正确的顺序返回项目.但是最有可能(您的问题中缺少相关的代码),当您将快照转换为字典(按定义是无顺序的)时,您将丢失该顺序.

The query returns the items in the correct order. But most likely (the relevant code seems to be missing from your question) you're losing that order when you convert the snapshot to a dictionary (which is unordered by definition).

要使项目保持正确的顺序,请遍历 snapshot.children :

To keep the items in the correct order, iterate over 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
      }        
})

另请参阅:

  • Firebase snapshot.key not returning actual key?
  • Firebase access keys in queryOrderBy
  • Retrieving Data using Firebase Swift
  • Iterate over snapshot children in Swift (Firebase) (I usually try to avoid allObjects, but it's fine too)

这篇关于在Swift中使用Firebase查询最新条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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