附加Firebase聊天消息

我正在创build一个聊天应用程序,我有一个表格视图单元格中两个用户之间发送的所有消息的列表。 例如,我在两个用户之间共有四个文本,所以我有四个单元格。 但是,我想将单元格分组,因此我只有一个单元格,因为我的loggedInUser只与一个人通信。 不pipe我做什么,邮件都不会追加。

func loadData(){ if (FIRAuth.auth()?.currentUser) != nil{ FIRDatabase.database().reference().child("messages").observeSingleEvent(of: .value, with: { (snapshot:FIRDataSnapshot) in let loggedInUserData = snapshot if let postsDictionary = snapshot .value as? [String: AnyObject] { for post in postsDictionary { let messages = post.value as! [String: AnyObject] for (id, value) in messages { let info = value as! [String: AnyObject] if let receiver = info["ReceiverId"] { print("\(id): \(receiver)") self.messages.Array(value) } } self.MessageTableView.reloadData() } }})} } 

截至目前我的应用程序正在这样的两个用户之间显示消息: 在这里输入图像说明

我认为这个问题是在self.messages.Array(value)我只需要在两个用户之间追加消息,但我找不到正确的代码

但我想要在两个用户之间的对话在一个单元格(附加它) 在这里输入图像说明

这是我的细胞看起来像:

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MessageCell", for: indexPath) as! MessageTableViewCell //Configure the cell print(messages[indexPath.row]) let message = self.messages[indexPath.row] as! [String: AnyObject] if let seconds = message["timestamp"] as? Double { let timeStampDate = NSDate(timeIntervalSince1970: seconds) let dateFormatter = DateFormatter() dateFormatter.dateFormat = "hh:mm a" cell.Time.text = dateFormatter.string(from: timeStampDate as Date) } cell.Message.text = message["text"] as? String // cell.SellerName.text = message["ReceiverId"] as? String if let imageName = message["ReceiverId"] as? String { let ref = FIRDatabase.database().reference().child("posts").child(imageName) ref.observeSingleEvent(of: .value, with: { (snapshot) in if let dictionary = snapshot.value as? [String: AnyObject]{ for post in dictionary { let messages = post.value as! [String: AnyObject] for (id, value) in messages { cell.SellerName.text = messages["username"] as? String if (messages["uid"] as? String) != nil { let uidPoster = messages["uid"] as? String let imageRef = FIRStorage.storage().reference().child((uidPoster)!+"/profile_pic.jpg") imageRef.data(withMaxSize: 25 * 1024 * 1024, completion: { (data, error) -> Void in if error == nil { let image = UIImage(data: data!) cell.UserPic.image = image cell.UserPic.layer.cornerRadius = 30 cell.UserPic.clipsToBounds = true }else { print("Error downloading image:" ) }})} self.messages.add(value) } } } }) } return cell } 

我的firebase消息的path是:

FIRDatabase.database()。参考()。子女( “信息”)。子女( “(self.convoId!)”)。childByAutoId()

这是我的数据库结构: 在这里输入图像说明

我将在我的答案中使用一个超级简单的例子。

给定一个结构

 messages msg_0 rec: "uid_0" send: "uid_1" msg: "msg from uid_0 to uid_1" msg_1 rec: "uid_1" send: "uid_0" msg: "msg from uid_1 to uid_0" 

将一个查询观察者添加到消息节点,观察具有一个rec:uid_0的新消息(.childAdded)。

 var messagesArray = [String]() func watch() { let messagesRef = self.ref.child("messages") let queryRef = messagesRef.queryOrdered(byChild: "rec").queryEqual(toValue: "uid_0") queryRef.observe(.childAdded, with: { snapshot in let msgDict = snapshot.value as! [String: Any] let msg = msgDict["msg"] as! String self.messagesArray = [] //erases the array self.messagesArray.append(msg) //adds this new message at index 0 print(self.messagesArray) //print is just for example //normally call tableView.reloadData() which will refresh // the cells in the tableView and display just once cell with // the latest message in it }) } 

您可以通过将快照或字典存储在数组中来进行推断,以便了解消息文本,并可以使用send:user id查找发送消息的人员。

如果你运行这个代码,输出将是任何新的消息发送到uid_0; 只会显示最新的信息。 如果你有一个带有messagesArray的tableView,因为它是dataSource(这通常是如何完成的),那么tableView将被刷新,并且只显示uid_0的最新消息。

作为一个侧面说明,.queryLimited(toLast :)可以在这里被利用是很好的。

1)我认为,在你的情况下,你应该.queryLimited(toLast:1)到每个聊天消息。 如果细节打开 – 加载其他消息。

2)但我有一个假设,你有错误的数据库结构。 检查这个

在这里,您可以findfirebase doc作者聊天的数据库结构。

你也可以检查这个旧的片段制作聊天应用程序: 链接

希望能帮助到你