ios - 附加 Firebase 聊天消息

标签 ios arrays swift firebase firebase-realtime-database

我正在创建一个聊天应用程序,我在表格 View 单元格中列出了两个用户之间发送的所有消息。例如,我在两个用户之间总共有四个文本,所以我有四个单元格。但是,我想对单元格进行分组,以便我只有一个单元格,因为我 loggedInUser 只与一个人通信。无论我做什么,消息都不会附加。

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()
}


}})}
}

截至目前,我的应用程序正在显示两个用户之间的消息,如下所示: enter image description here

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

但我希望两个用户之间的对话在一个单元格中(附加)enter image description here

这是我的手机的样子:

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 消息路径是:

FIRDatabase.database().reference().child("messages").child("(self.convoId!)").childByAutoId()

这是我的数据库结构:enter image description here

最佳答案

我将在我的回答中使用一个 super 简单的例子。

给定结构

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
    })
}

您可以通过将快照或字典存储在数组中据此进行推断,这样您就可以知道消息文本并可以使用发送:用户 ID 来查找发送消息的人。

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

作为旁注,.queryLimited(toLast:) 可以在这里很好地利用。

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

相关文章:

java - 无法在 int[] 上设置数字

javascript - 将 Javascript 对象和子对象转换为对象数组 - lodash

ios - 通过 iOS 登录 Facebook

ios - iTunes Connect 只有 "Get Started"屏幕

iOS WKWebView 不加载 http 网页内容

javascript - 比较二维数组与一维数组的值

arrays - 基于字符串数组对自定义数组进行排序

ios - Swift 3 中的 CAShapeLayer 点击检测

ios - backBarbuttonitem 什么都不做?

ios - Xcode 8 中的 Storyboard中缺少导航栏并显示 segue