我从json下载图像链接,然后在表格视图开始创建其单元格后创建图像:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCellController
DispatchQueue.main.async(execute: { () -> Void in
if let url = NSURL(string: self.movies[indexPath.row].image)
{
if let data = NSData(contentsOf: url as URL)
{
let imageAux = UIImage((data: data as Data))
cell.movieImage.image = imageAux
self.tableView.reloadData()
}
}
})
cell.name = self.movies[indexPath.row].name
cell.date = self.movies[indexPath.row].date
return cell
}
这样做很好,但是表格视图变得很慢,不是在渲染而是在滚动。我一直在检查RAM和CPU,两者都确实很低,但是我的网络使用率一直在上升,但是图像已经在单元中,所以这意味着它已经完成了。 (对于此测试,我仅调用了2部电影的JSON,因此只调用了2张图像)
在开始执行此操作之前,我的总下载量约为200kb(含图片),现在在我停止该项目之前,下载量已超过2MB。
我在做什么错?
最佳答案
您可能需要为后台 Activity 指定一个单独的队列。在这种情况下,您的繁重网络任务在:NSData(contentsOf: url as URL)
这就是“冻结” UI。最好的解决方案是定义类似DispatchQueue.background
的代码并在那里执行网络调用,然后稍后在主线程上执行UI任务,以免锁定您的显示:
DispatchQueue.background.async(execute: { () -> Void in
if let url = NSURL(string: self.movies[indexPath.row].image) {
//Do this network stuff on the background thread
if let data = NSData(contentsOf: url as URL) {
let imageAux = UIImage(data: data as Data)
//Switch back to the main thread to do the UI stuff
DispatchQueue.main.async(execute: { () -> Void in
cell.movieImage.image = imageAux
})
}
}
})
让我知道这是否有意义。
关于ios - 异步更新表单元格图像,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41814333/