问题描述
我正在使用带有Firebase实时数据库的iOS开发一个基本的聊天应用程序。
观察到的消息至少有10个限制。
现在,我想实现加载较早发送消息的功能。目前,我正在尝试通过使用以下功能来实现此目的:
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)
返回哪个查询:
(/vYhNJ3nNQlSEEXWaJAtPLhikIZi1/messages {
i = ".key";
l = 2;
sp = 2;
vf = r;
})
这应该给我数据:
query.observeSingleEvent(of: .value, with: { (snap) in
但是它只是限制了查询,而没有将起点设置到特定位置。
But it just limits the query and not set the start point to a specific position.
这是Firebase数据库结构:
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?
推荐答案
好吧,我终于找到了一种实现自己想要的方法的方法。
首先,我误解了从Firebase访问数据的方式。
现在这是查询的方式:
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)获取以前保存到自定义聊天消息中的FireBase密钥
1) get the FireBase key I previously saved to my custom chat messages
2)构建查询:
- 按键排序
- 将结尾设置为最早的邮件
- 将数组限制为查询所需的长度
然后实际获取我使用的查询:
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)以单个事件的形式获取查询
1) get the query as a single event
2)遍历孩子,我需要dropLast()以确保我不喜欢
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)将当前子级转换为FIRDataSnapshot以访问数据
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.
这篇关于使用自定义起点接收有限的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!