在集合视图中从服务器加载图像

时间:2018-10-01 14:32:44

标签: swift

我尝试了很多方法从集合视图中从服务器加载图像,但是滚动时仍存在滞后!

这是我的ImageProvider班:

let imageCache = NSCache<AnyObject, AnyObject>()

class ImageProvider: UIImageView {

    var imageUrl: String?

    func loadImage(from urlString: String) {
        self.imageUrl = urlString
        let url = URL(string: urlString)!
        image = nil

        if let imageFromCache = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
            self.image = imageFromCache
            return
        }

        URLSession.shared.dataTask(with: url) { (data, request, error) in
            if error != nil {
                print(error!)
                return
            }
            DispatchQueue.main.async {
                let imageToCache = UIImage(data: data!)
                if self.imageUrl == urlString {
                    self.image = imageToCache
                }
                imageCache.setObject(imageToCache!, forKey: urlString as AnyObject)
            }
        }.resume()
    }
}

设置数据:

func setupCVData(cell: TrackCell, item: Audio) {
        cell.title.text = item.name
        cell.url = URL(string: item.url!)!
        if let url = cell.url {
            var imageLink = String()
            (_, _, imageLink) = fetcher.getData(from: url)
            cell.imageUrl = imageLink
            cell.updateImageView()
        }
    }

updateImageView函数:

func updateImageView() {
        self.artwork.loadImage(from: imageUrl)
    }

我尝试在setupCVDatacollectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)中呼叫collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath)

我也没有运气使用过SDWebImage

那么我在这里做错了什么?我似乎无法解决问题。

1 个答案:

答案 0 :(得分:0)

据我所知,您不必在主线程上创建UIImage对象。我通常在后台线程中创建UIImage,而不会出现任何问题。但是,只能在主线程上修改UI元素。因此,当您设置UIImageView的image属性时,请确保在主线程上完成了该操作。

let imageToCache = UIImage(data: data!)
imageCache.setObject(imageToCache!, forKey: urlString as AnyObject)
DispatchQueue.main.async {
    if self.imageUrl == urlString {
       self.image = imageToCache
    }            
}