更新表格单元格图像异步

问题描述 投票:2回答:1

林从下载一个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无一不是相当低的,但我的网络使用不断上升,但图像是已经在细胞所以这意味着它已经完成。 (对于此测试IM调用JSON只有2电影,所以2个图像)

之前,我开始这样做我的总下载量为200KB左右(含图片),现在它得到了2MB之前,我停止该项目。

做什么我错了?

ios json swift asynchronous tableviewcell
1个回答
5
投票

你可能要指定一个独立的队列后台活动。在这种情况下,你的繁重的网络任务是:

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
            })
        }
    }
})

让我知道,如果这是有道理的。

© www.soinside.com 2019 - 2024. All rights reserved.