如何在 Swift 中过滤 Firebase 数据? [英] How to filter Firebase data in Swift?
问题描述
基本上,我有一个称为主题的结构,其中包含 Title
、Description
和 Published
标志(请参阅下面的屏幕截图以进行说明).
Basically, I have a structure called, topics which contains Title
, Description
and a Published
flag (see screenshot below for clarification ).
在应用程序中,我想过滤数据,只显示具有published = true
的主题.
In the application, I want to filter the data and only show the topics that have published = true
.
这就是我想要做的:
self.ref = FIRDatabase.database().referenceFromURL(FIREBASE_URL).child("topics")
self.ref?.queryEqualToValue("published")
self.ref?.observeEventType(.Value, withBlock: { (snapshot) in
//...Handle Snapshot here
})
但这行不通.我应该如何处理这个问题?预先感谢您的帮助.
But this is not working. How should I approach this? Thanks in advance for the help.
推荐答案
你有一些小错误.总体来说没什么太糟糕的,但结合起来他们永远不会工作:
You have a few small mistakes in there. Overall nothing too bad, but combined they'll never work:
- 调用任何
query...
方法都会返回一个新对象 - 你需要
orderByChild()
才能过滤它的值 - 你需要遍历结果
- calling any of the
query...
methods returns a new object - you need to
orderByChild()
before you can filter on its value - you need to loop over the results
结合这些:
let ref = FIRDatabase.database().referenceFromURL(FIREBASE_URL).child("topics")
let query = ref.queryOrderedByChild("published").queryEqualToValue(true)
query.observeEventType(.Value, withBlock: { (snapshot) in
for childSnapshot in snapshot.children {
print(childSnapshot)
}
})
我们经常收到这个问题.例如,昨天的这看起来非常相似:Firebase 查询未正确执行.由于我的解释因每个答案而异,我建议浏览一下以阅读我的 相关答案 直到它点击.
We get this question regularly. For example, this from yesterday looks very similar: Firebase Query not Executing Properly. Since my explanation varies with every answer, I recommend browsing a bit to read my relevant answers until it clicks.
这篇关于如何在 Swift 中过滤 Firebase 数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!