【发布时间】:2018-03-30 11:59:44
【问题描述】:
我正在编写需要在 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 冻结。
提前致谢。
【问题讨论】:
标签: ios swift uitableview socket.io