Swift使用Firebase在聊天中显示最后发送的消息 [英] Swift Showing last sent message in chat using firebase
问题描述
我正在尝试从情节提要中在聊天信使的主屏幕上显示我的上次发送的消息,如下所示:
I am trying to show my last sent message on my home screen of the chat messenger, from storyboard it looks like :
和我使用的代码是:
func getAllMsg() {
self.users = []
let fromId = Auth.auth().currentUser!.uid
let ref = Database.database().reference().child("privateMessages").child(fromId)
ref.observeSingleEvent(of: .value) { (snapshot) in
for snap in snapshot.children.allObjects as! [DataSnapshot] {
// retrieving receiver's ID
let chatUserID = snap.key
let ref2 = Database.database().reference().child("users").child(chatUserID)
// to retrieve message ID
ref2.observeSingleEvent(of: .value, with: { (snapshot2) in
let newUser = User(dictionary: snapshot2.value as! [String: AnyObject])
// to get the last message
ref.child(chatUserID).queryLimited(toLast: 1).observeSingleEvent(of: .value, with: { (snapshot3) in
let value = snapshot3.children
while let rest = value.nextObject() as? DataSnapshot {
newUser.lastMessage = (rest.value as! [String: AnyObject])["textMessages"] as? String
self.users.append(newUser)
DispatchQueue.main.async {
self.tableView.reloadData()
}
break
}
})
})
}
}
}
我对数据库进行了一些更改,并且上面的代码起作用了,但是当我改变了数据库的处理方式后,它不再起作用了以前,我的firebase看起来像
I have done some changes to my database and the above codes works, but after i changed the way i do my database, it doesnt work anymore previously, my firebase looks like
现在我的firebase看起来像:
now my firebase looks like:
我通过使用发送者和接收者ID设置了chatRoomId.但是我现在无法显示应该在主屏幕上显示的最后发送的消息.我有什么办法可以解决这个问题?还是我获取数据库的方式错误?
i made a chatRoomId by using send and receiver ID. however I am now not able to show my last sent message which was supposed to show on my homescreen. Any ways I can go about this? Or the way I fetched my database is wrong?
推荐答案
根据您的数据库结构,您的查询错误.也不要在其他查询的块内执行 lastMessage
查询,因为这是完全独立的查询,与任何查询都不相关.下面的代码将为您工作.
Your query is wrong according to your db structure. Also don't perform lastMessage
query inside the block of other query because this is totally independent query and not related with any. Below piece of code will work for you.
let ref = kFirDefaultDatabase.reference().child("yourChatRoomId").queryOrdered(byChild: "fromId").queryEqual(toValue: "0YfqnPIOYFYKb8cYZMHnSYti62i2").queryLimited(toLast: 1)
ref.observeSingleEvent(of: DataEventType.value) { (snapshot) in
if snapshot.exists() {
print(snapshot.value)
}
}
这将为请求的 chatRoomId
获取 fromId
发送的最后一条消息.有关更多详细信息,请参见 Firebase查询文档.
This will fetch the last message sent by fromId
for the requested chatRoomId
. For more detail have a look at Firebase Queries doc.
如果您想在表中为所有用户(例如 WhatsApp
或其他聊天应用程序)执行此操作,则需要制作一个额外的表 LastMessages
并保存最后一条消息与每个 chatRoomId
相对应的此处信息,或者如果可能的话,将该详细信息保存在您可以通过 tableData
获取的某个地方,这样就无需查询每个 chatRoom 代码>.
And if you want to do this in table for all users like in WhatsApp
or other chatting application then you will need to make an extra table LastMessages
and save last message information here corresponding to each chatRoomId
or if possible save this detail somewhere you can fetch with the tableData
so that you don't need to query for each chatRoom
in a loop.
您可以做一些更好的事情以使其更快.每当您发送或接收任何消息时,使用 CoreData
或 Sqlite
并将 lastMessage
信息保存/更新到 local db
中,其中 chatRoomId
将是一个主键
,并首先从 local db
获取信息,并立即在 table
中显示并表示同时您可以从服务器获取数据并更新本地数据库
并刷新表
.
You can do some better stuff to make it faster. Use CoreData
or Sqlite
and save/update lastMessage
information into local db
whenever you send or received any message, where chatRoomId
will be a primary key
and first get the information from local db
and show in the table
immediately and mean while you can fetch the data from server and update your local db
and refresh the table
.
编辑:对于注释 以获得最后一条消息,无论我发送给收件人还是收件人发送给我
.
For comment to get the last message regardless I send to recipient or recipient send to me
.
删除 orderBy
查询,只需使用 limitToLast
.参见下面的代码:
Remove orderBy
query and just use limitToLast
. See below code:
let ref = kFirDefaultDatabase.reference().child("yourChatRoomId").queryLimited(toLast: 1)
ref.observeSingleEvent(of: DataEventType.value) { (snapshot) in
if snapshot.exists() {
print(snapshot.value)
}
}
这篇关于Swift使用Firebase在聊天中显示最后发送的消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!