1

I am trying to get data from firebase database using firebase query

self.getReferencePath().child(User.followingReferencePath).queryOrderedByKey().queryLimited(toLast: 5)

When I pass this query to firebase and print the snapshot.value, I get the data in the order present in firebase as following

snapshot.value {
"-L2_hNtqB5UCBzgMFX0m" =     {
    "debate_id" = "-L2_hNtqB5UCBzgMFX0m";
};
"-L2_hSQSl7T5cDCfDoiV" =     {
    "debate_id" = "-L2_hSQSl7T5cDCfDoiV";
};
"-L2_h_vrwqID5Esl6gOk" =     {
    "debate_id" = "-L2_h_vrwqID5Esl6gOk";
};
"-L2_hfAruruMjzrLEZtI" =     {
    "debate_id" = "-L2_hfAruruMjzrLEZtI";
};
"-L2_hk2Uq7IBcflkO5YQ" =     {
    "debate_id" = "-L2_hk2Uq7IBcflkO5YQ";
};
}

But after converting the snapshot.all values as NSArray, the order changes as follow

let followingDbate = followingDebatesSnapshot.allValues as NSArray
print("followingDbate",followingDbate)

followingDbate (
    {
    "debate_id" = "-L2_hk2Uq7IBcflkO5YQ";
},
    {
    "debate_id" = "-L2_h_vrwqID5Esl6gOk";
},
    {
    "debate_id" = "-L2_hfAruruMjzrLEZtI";
},
    {
    "debate_id" = "-L2_hNtqB5UCBzgMFX0m";
},
    {
    "debate_id" = "-L2_hSQSl7T5cDCfDoiV";
}
)

I want to get the last Id as=nd pass it through another query. As the order changes I am not able to get the last id correctly. Please advice how to get the data without changing the order and also ow to get the last id from the snapshot I get. Thanks in advance

Mohanraj
  • 587
  • 4
  • 21
  • you are using queryOrderedByKey() , try removing it, you will get the correct results. Just use : Path().child(User.followingReferencePath).queryLimited(toLast: 5) – Pallavi Srikhakollu Jan 17 '18 at 11:24
  • tried it.. still same result @PallaviSrikhakollu – Mohanraj Jan 17 '18 at 11:43
  • A dictionary cannot maintain the order of the children in a snapshot, so the order is lost as soon as you call `allValues`. The solution is to iterate over `allObjects` instead, as shown here: https://stackoverflow.com/questions/27341888/iterate-over-snapshot-children-in-swift-firebase – Frank van Puffelen Jan 17 '18 at 15:52

0 Answers0