Firebase queryEqualToValue get Key in Swift 2.3

*爱你&永不变心* 提交于 2019-12-25 08:18:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!