2

I have an app, that has Topics and categories, one category may belong to one or more topics, i'm trying to filter the data to only show category that has a certain topic id marked as true, this is the structure: enter image description here Categories with references to the topics ID.

Here is the code i come up with ( which was working on Swift 2.3 ):

self.ref = FIRDatabase.database().reference(fromURL: FIREBASE_URL).child("categories")
let query = ref?.queryOrdered(byChild: "topics/idt2").queryEqual(toValue: true)
query!.observe(.value, with: { (snapshot) in
    //This should bring back both categories, Soccer and Moon

    print("Inside query \(snapshot.value)") // Prints null

})

Any ideas?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
André Oliveira
  • 1,105
  • 4
  • 20
  • 53
  • Fox a next question: You've included a picture of the JSON tree in your question. Please replace that with the actual JSON as text, which you can easily get by clicking the Export button in your Firebase Database console. Having the JSON as text makes it searchable, allows us to easily use it to test with your actual data and use it in our answer and in general is just a Good Thing to do. – Frank van Puffelen Oct 01 '16 at 23:27

1 Answers1

3

When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

You will need to handle this list in your callback block:

query!.observe(.value, with: { (snapshot) in
    for child in snapshot.children {
        print(child.key)
    }
})

Also see:

Community
  • 1
  • 1
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 1
    Once again thanks for the help, just a little detail, this code is not working in Swift 3.0, correct me if i'm wrong but now to use the values from snapshot, you to convert it first to a NSDictionary or NSArray, something like this: http://pastebin.com/f7q8kbvJ – André Oliveira Oct 02 '16 at 01:30