Joon Choi Joon Choi - 1 month ago 62
Swift Question

Firebase queryEqualToValue get Key in Swift 2.3

I am developing a small application in iOS using Swift and Firebase. I am having trouble querying a data and retrieving the value.
My firebase realtime database is this:

"qrcode" : {
"postsedation_room" : "http://bing.com",
"preprocedure_room" : "http://google.com",
"presedation_room" : "http://en.m.wikipedia.org"
}


I would like to make this query :

let query = rootRef.child("qrcode").queryEqualToValue("http://bing.com")

query.observeSingleEventOfType(.Value, withBlock: { snapshot in
print(snapshot)
})


print a key value "postsedation_room".
At this point the result of print is
Snap (qrcode) <null>
could you help me so that I can print key given the child value?

Answer

When you execute a query against the Firebase Database, there will potentially be multiple results. So if you attach a value observer 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.

So in your observer you'll need to handle that list. The easiest way to do that is to iterate over it:

let query = rootRef.child("qrcode").queryOrderedByValue().queryEqualToValue("http://bing.com")

query.observeSingleEventOfType(.Value, withBlock: { snapshot in
   for child in snapshot.children {
      print(child.key)
   }
})

Alternatively you can observe a single childAdded eventL

let query = rootRef.child("qrcode").queryEqualToValue("http://bing.com")

query.observeSingleEventOfType(.ChildAdded, withBlock: { snapshot in
   print(snapshot.key)
})