在我的聊天功能中,我在表格 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/