gpt4 book ai didi

swift - 如何初始加载 UITableView 然后观察 Firebase 节点的更改以在 Swift 中刷新 tableview?

转载 作者:行者123 更新时间:2023-11-30 10:44:12 28 4
gpt4 key购买 nike

我正在加载一个UITableView,其中的User数据最初是使用observeSingleEventFirebase获取的,据我所知,初次读取后不附加观察者。

每个单元格中还有一个图标,当用户在线/离线时该图标会更新。为此,我将观察者附加到 observewillDisplay 单元委托(delegate)方法中特定 User 子节点的任何更改,并在didEndDisplaying 方法。

这是我第一次执行此操作并且工作正常,但在继续之前我想知道这是否是最初加载数据然后观察更改以便可以针对每个单元格相应更新 View 的行业标准方法。

cellForRowAt 方法使单元出列并配置:

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

guard let cell = tableView.dequeueReusableCell(withIdentifier: "ConversationsListCell", for: indexPath) as? ConversationsListCell else { return UITableViewCell() }

let message = messages[indexPath.row]


DataService.run.getUserInfo(forUserId: message.chatPartnerId()!) { (user) in
cell.configureCell(message: message, user: user)
}
return cell

}//end func

willDisplay 方法在特定子节点上附加一个观察者,并在该节点发生任何更改时触发 tableView.reload():

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

let message = messages[indexPath.row]

DataService.run.observeUserNodeChages(forId: message.chatPartnerId()!) { (user) in
self.tableView.reloadData()
}

}//end func

didEndDisplaying 方法删除 willDisplay 方法附加的观察者:

func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {

if indexPath.row < messages.count {

let message = messages[indexPath.row]
DataService.run.removeObserveUserNodeChages(forId: message.chatPartnerId()!)
}

}//end func

observeUserNodeChages 监听特定 uid 子节点的任何更改

func observeUserNodeChages (forId: String, handler: @escaping (Bool) -> ()){

print("inside observeUserNodeChages forId:\(forId)")

conversationListHandle = REF_USERS.child(forId).observe(.childChanged, with: { (snapshot) in

handler(true)

}, withCancel: nil)

}//end func

用户节点 Firebase 结构

enter image description here

最佳答案

I want to know if this is the industry standard way

这不是行业标准方式,应该避免,因为它会导致 UI 闪烁和响应缓慢。然而,在编码方面,通常不存在“标准”,因为您为解决问题而编写的代码会根据用例和所需结果而有所不同。

您的 tableView 数据源最初应从 Firebase 填充,然后在发生更改时进行更新;这将由 Firebase 事件启动。更新 dataSource 后,刷新 tableView。

这将使应用程序保持响应并让您的用户满意。

另一件事是您似乎在同一个(用户)节点中附加了多个观察者。这可能没有必要;将您的观察者附加到/users 节点,然后您将收到添加、更改或删除事件的通知,并且受影响的用户将作为快照传递到 firebase 闭包。

关于swift - 如何初始加载 UITableView 然后观察 Firebase 节点的更改以在 Swift 中刷新 tableview?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56124275/

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