ios - 在 TableView 单元格中处理从 Firebase 检索数据的更好方法

标签 ios swift firebase google-cloud-firestore

在我的聊天功能中,我在表格 View 中向当前用户显示他与其他用户的聊天记录。 tableview 上的每个单元格都是对方用户的信息、头像和姓名。将这些信息存储在聊天对象中很容易,但问题是对方用户此时可能已经更改了他的头像或名称。

因此,我在聊天的单元格配置中获取对方用户的头像和姓名。它工作正常,但我不确定是否有更好的方法,因为我不赞成在每个单元格中进行 Firebase 网络调用。

这里是我的cell配置方法:

    func configureCell(from chat: Chat){
    // 1st Get opposite user id
    if let currentUser = Auth.auth().currentUser{
        let user1 = chat.people.first
        let user2 = chat.people.last
        let user1Id = user1?["id"] ?? ""
        let user2Id = user2?["id"] ?? ""
        var oppositeUserId = ""
        if user1Id == currentUser.uid{
            oppositeUserId = user2Id
        }else{
            oppositeUserId = user1Id
        }
        //2nd Fetch opposite user doc
        let oppositeUserDocRef = References.Instance.getUserDocRef(for: oppositeUserId)
        oppositeUserDocRef.getDocument { (oppositeUserDocSnapshot, error) in
            if error != nil{
                print("ERROR FETCHING OPPOSITE USER DOC:: ERROR IS:  \(error?.localizedDescription ?? "")")
                return
            }
            // 3rd get opposite user avatar url and name
            if let otherUserDic = oppositeUserDocSnapshot?.data(){
                if let avatarDic = otherUserDic["avatar"] as? [String: String]{
                    let avatarUrl = avatarDic["url"] ?? ""
                    self.avatarView.sd_setImage(with: URL(string: avatarUrl),
                                          placeholderImage: nil, options: .refreshCached)
                }
                if let name = otherUserDic["name"] as? String{
                    self.uiLabelChatTitle.text = name
                }
            }
        }
    }
}

最佳答案

我从来没有真正使用过 Firebase,但对于这样的事情,我会说在单个网络请求中填充一个“chatDetails”对象数组,然后配置每个可重用单元格

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let chat = self.chatDetails[indexPath.row]

        let cell = tableView.dequeueReusableCell(withIdentifier: "identifier") as! ChatDetailsCell

        cell.configureCell(chat: chat)

        return cell

    }

关于ios - 在 TableView 单元格中处理从 Firebase 检索数据的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59836528/

相关文章:

ios - 为 UIBezierPath 创建旋转动画

swift - 如何在 Swift 中生成一个范围内的不同随机数?

ios - 使用按钮将文本添加到 UITableViewcell 中包含的文本字段值

objective-c - 在运行时更改枚举值?

ios - 带日期选择器的 UITextView

php - 当应用程序未在 swift 中运行时,iOS 会收到来自 google GCM 的推送通知

image - 有没有办法让 iPhone 应用程序只让用户下载他们的设备分辨率所需的图形?

javascript - Firebase Auth - 用户在 Firebase 注册和重定向后未登录

javascript - Google Cloud Functions 图像处理需要几分钟的时间进行图像处理

javascript - 如何在 Firebase 中获取网站的 gcm_sender_id