Receive limited query with custom start point

☆樱花仙子☆ 提交于 2019-12-11 05:57:37

问题


I'm building a basic chat app with swift for iOS with firebase realtime database. The Messages are observed with a limit for the least 10. Now, I want to implement the functionality of loading earlier send messages. Currently I'm trying to achieve this by using this function:

let query = threadRef.child("messages").queryOrderedByKey().queryStarting(atValue: "2").queryLimited(toLast: 2)

Which returns this query:

(/vYhNJ3nNQlSEEXWaJAtPLhikIZi1/messages {
   i = ".key";
   l = 2;
   sp = 2;
   vf = r;
})

And this should give me the data:

query.observeSingleEvent(of: .value, with: { (snap)  in

But it just limits the query and not set the start point to a specific position.

Here is the firebase database structure:

messages
   -Kgzb3_b26CnkTDglNd8
     date: 
     senderId: 
     senderName: 
     text: 
   -Kgzb4Qip6_jQdKRWFey
   -Kgzb4ha0KZkLZeBIaxW
   -Kgzb577KlNKOHxsQo9W
   -Kgzb5cqIVMhRmU019Jf

Anyone have an idea on how to implement a feature like that?


回答1:


Okay I finally found a way to do what I wanted. First of all I misunderstood the way to access data from Firebase. This is now how I get the query:

let indexValue = messages.first?.fireBaseKey
let query = messageRef.queryOrderedByKey().queryEnding(atValue:indexValue).queryLimited(toLast: 3)

1) get the FireBase key I previously saved to my custom chat messages

2) construct the query:

  • order it by key
  • set the ending to oldest message
  • limit the array to query to desired length

Then to actually get the query I used:

 query.observeSingleEvent(of: .value, with: { snapshot in
    for child in snapshot.children.dropLast().reversed() {
       let fireSnap = (child as! FIRDataSnapshot)
       //do stuff with data
    }
})

1) get the query as a single event

2) iterate over children and I needed to dropLast() to make sure I don't have any duplicated messages and reverse it to get the correct order.

3) cast the current child as a FIRDataSnapshot to access the data

Since I couldn't find a simple example for this so I thought I leave my solution here incase other people running into the same problem.



来源:https://stackoverflow.com/questions/43252596/receive-limited-query-with-custom-start-point

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