André André - 5 months ago 56
Swift Question

How to filter Firebase data in Swift?

Basically, I have a structure called, topics which contains

and a
flag (see screenshot below for clarification ).

Topics object in Firebase Database

In the application, I want to filter the data and only show the topics that have
published = true

This is what I'm trying to do:

self.ref = FIRDatabase.database().referenceFromURL(FIREBASE_URL).child("topics")
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:

  1. calling any of the query... methods returns a new object
  2. you need to orderByChild() before you can filter on its value
  3. you need to loop over the results

Combining these:

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 {

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.