gpt4 book ai didi

ios - 在 iOS 中处理数以千计的套接字消息

转载 作者:搜寻专家 更新时间:2023-10-31 23:07:30 25 4
gpt4 key购买 nike

我正在编写一个代码,我需要在其中显示套接字消息在 tableview 中,并且 tableview 以缓慢的动画滚动到底部。我处理了这个问题,但是如果继续从套接字加载消息(考虑每秒 20/30 条消息),那么 UI 会卡住。我需要像 Facebook 那样在实时屏幕上每次迭代显示一条或两条消息。

这是我的代码

override func viewDidLoad() {
super.viewDidLoad()
Timer.scheduledTimer(timeInterval: 0.025, target: self, selector: #selector(self.scrollTableView(_:)), userInfo: nil, repeats: true)
self.designLayout()

}

@objc func scrollTableView(_ timer: Timer) {

guard messagesData.count > 0 else {
return
}
if tableView.contentSize.height > tableView.bounds.height {
tableView.contentInset.top = 0
}
tableView.scrollToRow(at: IndexPath(row: messagesData.count - 1, section: 0), at: UITableViewScrollPosition.bottom, animated: true)

}
self.socket.on(“key”) {data, ack in
print("data type is \(type(of: data))")
let arrayValue = data as Array<Any>
DispatchQueue.global(qos: .background).async {
self.handleCountsAndMessaging(data: arrayValue)
}
}

func handleCountsAndMessaging(data: Array<Any>) {
if let arrData = data[0] as? NSMutableDictionary {
if(arrData.object(forKey: "text") != nil) {
self.tableDataLoading(str: String(describing: arrData.object(forKey: "text")!))
}
}
}

func tableDataLoading() {
print ("sttttttt \(str)")
DispatchQueue.main.async {
self.messagesData.add(str)
self.tableView.reloadData()
}
}

有时我从套接字中一次收到 200 条消息,在处理之前的消息时再次收到 200 条消息,CPU 消耗显示为 120 条,UI 卡住。

提前致谢。

最佳答案

好吧,有'live'和'live':)这是我们正在谈论的手机,所以每 0.025 秒更新一次屏幕是没有用的……您可以轻松地减慢获取时间,但让我们一次解决一个问题:

1/不要使用 tableView.scrollToRow,而是使用“insertRows(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation)”来插入新行,这样如果你的用户正在阅读,他就不会了。如果您添加 200 个新项目,请不要打扰 https://developer.apple.com/documentation/uikit/uitableview/1614879-insertrows

2/放慢你的 UI 更新,你过度使用你的主线程...如果你愿意,你可以每 25 毫秒获取一次,但我建议使用节流机制仅在你获得新内容时更新 UI,并且仅当上次 UI 更新不少于 5 秒前。

关于ios - 在 iOS 中处理数以千计的套接字消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49574039/

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