问题
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?
回答1:
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)
})
来源:https://stackoverflow.com/questions/40316200/firebase-queryequaltovalue-get-key-in-swift-2-3