gpt4 book ai didi

ios - 聊天消息未正确加载

转载 作者:行者123 更新时间:2023-11-28 07:45:40 26 4
gpt4 key购买 nike

我尝试创建一个聊天消息系统,但是当调用新消息时,旧消息似乎仍然存在。

Error picture here

有人可以帮忙吗?此外,有时当创建新用户并与另一个用户聊天时。来自其他用户的消息不会反射(reflect)在新用户聊天中。

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationItem.title = "Chat"
DispatchQueue.global(qos:.userInteractive).async {
DispatchQueue.main.async {
self.loadPosts()
self.loadPostsReceivedMessage()
}
}
}

//Get Message sent
func loadPosts() {
let senderIDNumber = Auth.auth().currentUser?.uid
let chatsRef = db.collection("chats").order(by: "timestamp", descending: false)
chatsRef.whereField("senderID", isEqualTo: senderIDNumber!).whereField("receiverID", isEqualTo: receiverIDNumber)
.addSnapshotListener { querySnapshot, error in
guard let documents = querySnapshot?.documents else {
print("Error fetching documents: \(error!)")
return
}
for document in documents {
let messageText = document.data()["message"] as? String
let senderIDNumber = document.data()["senderID"] as? String
let receiverIDNumber = document.data()["receiverID"] as? String
let timestamp = document.data()["timestamp"] as? String
guard let sender = document.data()["sender"] as? String else {return}
// let conversationsCounter = document.data()["conversationsCounter"] as? Int
guard let profileUrl = document.data()["profileUrl"] as? String else { return}
let chat = Chat(messageTextString: messageText!, senderIDNumber: senderIDNumber!, receiverIDNumber: receiverIDNumber!, timeStampString: timestamp!, profileImageUrl: profileUrl, senderString: sender)
self.chats.append(chat)
print(self.chats)
self.collectionView.reloadData()
}
}
}


//Get message received
func loadPostsReceivedMessage() {
/* let uid = Auth.auth().currentUser?.uid
let ref = Database.database().reference()
ref.child("users").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in
if let dic = snapshot.value as? [String: AnyObject]{
let currentUser = dic["username"] as? String
let senderIDNumber = Auth.auth().currentUser?.uid
} */
let chatsRef = db.collection("chats").order(by: "timestamp", descending: false)
print("thecurrentreceiver"+senderString)
print("thecurrentsender"+receiverIDNumber)
chatsRef.whereField("receiverID", isEqualTo: senderString).whereField("sender", isEqualTo: receiverIDNumber)
.addSnapshotListener { querySnapshot, error in
guard let documents = querySnapshot?.documents else {
print("Error fetching documents: \(error!)")
return
}
for document in documents {
let messageText = document.data()["message"] as? String
let senderIDNumber = document.data()["senderID"] as? String
let receiverIDNumber = document.data()["receiverID"] as? String
let timestamp = document.data()["timestamp"] as? String
// let conversationsCounter = document.data()["conversationsCounter"] as? Int
guard let profileUrl = document.data()["profileUrl"] as? String else { return}
guard let sender = document.data()["sender"] as? String else {return}
let chat = Chat(messageTextString: messageText!, senderIDNumber: senderIDNumber!, receiverIDNumber: receiverIDNumber!, timeStampString: timestamp!,profileImageUrl: profileUrl, senderString: sender)
print("whatisthemessage"+messageText!)
self.chats.append(chat)
print(self.chats)
self.chats.sort{$0.timestamp < $1.timestamp}
self.collectionView.reloadData()
}
}
}

最佳答案

您正在使用 addSnapshotListener,这意味着每次数据库中的相关内容发生变化时都会调用您的回调。当发生这种情况时,您将遍历所有与您的查询匹配的文档并将它们添加到您的 View 中。这意味着如果有多项更改,您将多次添加大多数消息。

有两种常见的解决方案:

  1. 每次调用回调时清除 View 。
  2. 仅在每次调用您的回调时针对更改修改 View 。

我们将使用下面的 #2,因为它更有效率。请注意,我只是处理新消息以使事情简单化。当您使您的应用程序更加完善时,您还需要处理其他类型的更改,例如当用户删除或更新聊天消息时。

let chatsRef = db.collection ("chats").order (by: "timestamp", descending: false)
chatsRef.whereField ("senderID", isEqualTo: senderIDNumber!)
.whereField ("receiverID", isEqualTo: receiverIDNumber)
.addSnapshotListener {
querySnapshot,
error in guard let documentChanges = querySnapshot?.documentChanges else {
print ("Error fetching documents: \(error!)")
return
}
for documentChange in documentChanges {
if (documentChange.type == .added) {
let data = documentChange.document.data ()
let messageText = data["message"] as? String
let senderIDNumber = data["senderID"] as? String
let receiverIDNumber = data["receiverID"] as? String
let timestamp = data["timestamp"] as? String
...

let chat = Chat (
messageTextString : messageText!,
senderIDNumber : senderIDNumber!,
receiverIDNumber : receiverIDNumber!,
timeStampString : timestamp!,
profileImageUrl : profileUrl,
senderString : sender
)
self.chats.append (chat)
print (self.chats)
self.collectionView.reloadData ()
}
}
}

有关此的更多信息,请查看 responding to changes在 Firebase 文档中。

关于ios - 聊天消息未正确加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51124112/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com