iOS - Firebase Filter query

别等时光非礼了梦想. 提交于 2020-01-21 06:13:46

问题


I got score node in Firebase:

And under score node my data structure is as:

{
"jjTO29ziQ2SjrH5PFzY7ZMpSgjq1-Kak6FCyGtdy_kcEPd4K" =     {
    jjTO29ziQ2SjrH5PFzY7ZMpSgjq1 = "-Kak6FCyGtdy_kcEPd4K";
    score = 5;
};
"jjTO29ziQ2SjrH5PFzY7ZMpSgjq1-KbE_pgfUsukOm4uW0bx" =     {
    jjTO29ziQ2SjrH5PFzY7ZMpSgjq1 = "-KbE_pgfUsukOm4uW0bx";
    score = 4;
};

Question: Can I filter the data by score ?

I tried doing :

FIRDatabase.database().reference().child("scores").queryOrdered(byChild: "score").observeSingleEvent(of: .value, with: { (snapshot) in

        debugPrint(snapshot.value ?? "nil")

    })

But can't get the result ?


回答1:


When you execute a query against Firebase, you get a FIRDataSnapshot that contains three pieces of information for each result:

  • its key
  • its value
  • its position relative to other nodes

When you're calling snapshot.value the snapshot is converted into a Dictionary. Unfortunately that dictionary can only hold key-value pairs, so you lose the information on the position of the nodes. So while the data in the snapshot is actually sorted correctly, you're throwing that information away.

The solution is to use the FIRDataSnapshots built-in children property to loop over the child nodes in the correct order. The Firebase documentation on querying has this sample of how to do that:

_commentsRef.observeEventType(.Value, withBlock: { snapshot in
  for child in snapshot.children {
    ...
  }
})


来源:https://stackoverflow.com/questions/41850535/ios-firebase-filter-query

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