André André - 1 year ago 106
Swift Question

How to filter Firebase data using Swift

Basically i have a structure called, topics which contains, Title, Description and a Published flag ( see screenshot below for clarification ).

Topics object in Firebase Database

In the Application and 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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download