当滚动甚至存储在 NSCache 中时,UIImage 始终保持加载 - swift

UIImage keeps loading all time when scroll even store in NSCache - swift

我是 iOS 编程新手。我正在创建一个简单的应用程序,它从特定的 link ( firestore ) 加载图像。图像完全从服务器下载,并且像往常一样在 collectionview 的每个单元格中可见。但问题是,当我向上或向下滚动时,这些图像会再次加载。我认为它再次开始下载,因为当我关闭互联网连接时,这些图像不再被加载。

这是我在每个单元格中设置图像的方法

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! CollectionCell

    let explore = dataAppend[indexPath.item]
    //cell.imageDisplay.text = explore.title
    if let imageUrl = explore.image {
        cell.imageDisplay.loadImageWithData(urlString: imageUrl)
    }
    //print(explore.image)
    return cell
}

这是加载图片的样子loadImageWithData(urlString: imageUrl)

let imageCache = NSCache<NSString, UIImage>()

class CustomImageView : UIImageView {

var imageUrlString: String?

func loadImageWithData (urlString: String) {

    imageUrlString = urlString
    if let imageFromCache = imageCache.object(forKey: urlString as NSString){
        self.image = imageFromCache
    }
    image = nil
    let url = URL(string: urlString)
    URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in

        if let err = error {
            print(err.localizedDescription)
        }
        if let data = data {

            DispatchQueue.main.async {
                let imageToCache = UIImage(data: data)
                if self.imageUrlString == urlString {
                    self.image = imageToCache
                }
                imageCache.setObject(imageToCache!, forKey: urlString as NSString)
            }
        }
    }).resume()
}
}
 var imageCache = NSMutableDictionary()

class CustomImageView: UIImageView {

func loadImageUsingCacheWithUrlString(urlString: String) {

    self.image = nil

    if let img = imageCache.valueForKey(urlString) as? UIImage{
        self.image = img
         return 
    }
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithURL(NSURL(string: urlString)!, completionHandler: { (data, response, error) -> Void in

            if(error == nil){

                if let img = UIImage(data: data!) {
                    imageCache.setValue(img, forKey: urlString)    // Image saved for cache
                    DispatchQuee.main.asyn{
                       self.image = img

                }


            }
        })
        task.resume()
    }
}

}

您可以改为使用 Kingfisher 库,自行处理图像缓存,您无需担心。实施见: https://github.com/onevcat/Kingfisher

只需一行代码即可设置图片

imgView.kf.setImage(with: ImageResource(downloadURL: URL(string: imgUrl)!))