Daniel Chepenko
Daniel Chepenko

Reputation: 2268

How to retrieve objects from firebase by key value

I'm new to firebase and I have such structure of my firebase project

enter image description here

I want to get all objects, that "Interested" value is equal to "men"

I wrote such code, to get all object sorted by interes value:

let thisUserRef = URL_BASE.childByAppendingPath("profile")

thisUserRef.queryOrderedByChild("Interest")
     .observeEventType(.Value, withBlock: { snapshot in

     if let UserInterest = snapshot.value!["Interest"] as? String {    
          print (snapshot.key)  
     }
}

But I receive nil.

Upvotes: 1

Views: 8380

Answers (2)

Jay
Jay

Reputation: 35667

This is a basic query in Firebase. (Updated for Swift 3, Firebase 4)

    let profileRef = self.ref.child("profile")
    profileRef.queryOrdered(byChild: "Interest").queryEqual(toValue: "men")
    profileRef.observeSingleEvent(of: .value, with: { snapshot in

        for child in snapshot.children {
            let dict = child as! [String: Any]
            let name = dict["Name"] as! String
            print(name)
        }
    })

The legacy documentation from Firebase really outlines how to work with queries: find it here

Legacy Firebase Queries

The new documentation is pretty thin.

Oh, just to point out the variable; thisUserNode should probably be profileRef as that's what you are actually query'ing.

Upvotes: 1

Shubhank
Shubhank

Reputation: 21805

you need to loop through all the key-value profiles

      if let allProfiles = snapshot.value as? [String:AnyObject] {
            for (_,profile) in allProfiles {
                  print(profile);
                  let userInterest = profile["Interest"]
           }
       }

Here _ is the key that is in the format KYXA-random string and profile will be the element for that key.

Edit:

There is querying for child values as per the docs.

Try thisUserRef.queryOrderedByChild("Interest").equalTo("men") and then using the inner loop that i specified in the answer

Upvotes: 3

Related Questions