Xcode我收集视图我在cellForRowAtIndexpath函数内将urlsession数据任务排队

时间:2019-03-06 14:14:15

标签: swift xcode urlsession

这是在indexpath.row,URL和urlSession处获取单元格的imageView的代码。但是它一次下载所有内容,这并不好。我只想在完成下载之前启动一个新的urlsession。我该怎么做?

    let image = cell.viewWithTag(10) as! UIImageView
    let url = URL(string: categories[indexPath.row].imageURL)
    URLSession.shared.dataTask(with: url!) { (data, response, error) in
        if error != nil {
            print(error!)
        }
        DispatchQueue.main.async {
            UIView.transition(with: image, duration: 0.1, options: .transitionCrossDissolve, animations: {
                image.image = UIImage(data: data!)
            }, completion: nil)
        }
        }
        .resume()

1 个答案:

答案 0 :(得分:0)

cellForRowAtIndexpath在单元格即将显示时被调用,因此在您当前的代码中,它将下载单元格每一个外观的图像,您需要使用SDWebImage来利用很多东西包括自动缓存

另外,最好为单元格内的元素而不是标签创建出口

let image = cell.viewWithTag(10) as! UIImageView