Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter Firebase data in 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, 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?.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.

like image 872
André Oliveira Avatar asked Sep 22 '16 19:09

André Oliveira


People also ask

How do you filter data in firebase realtime database?

We can filter data in one of three ways: by child key, by key, or by value. A query starts with one of these parameters, and then must be combined with one or more of the following parameters: startAt , endAt , limitToFirst , limitToLast , or equalTo .

What is uf8ff firebase?

The character \uf8ff used in the query is a very high code point in the Unicode range (it is a Private Usage Area [PUA] code). Because it is after most regular characters in Unicode, the query matches all values that start with queryText .

How do I get data from Firebase authentication?

If the user is authenticating and exists, you will know their uid so you can read in their node from /users. There is a Firebase web view for your data, it's called the Firebase Dashboard and can be accessed once you log into your account on the Firebase website.


2 Answers

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 {
        print(childSnapshot)
    }
})

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.

like image 78
Frank van Puffelen Avatar answered Sep 17 '22 17:09

Frank van Puffelen


self.ref = FIRDatabase.database().referenceFromURL(FIREBASE_URL).child("topics").
    queryOrderedByChild("published").queryEqualToValue(true)
    .observeEventType(.Value, withBlock: { (snapshot) in
    for childSnapshot in snapshot.children {
        print(snapshot)
    }
})
like image 23
Traveler Avatar answered Sep 20 '22 17:09

Traveler