ios - Swift 图像缓存不重新加载

标签 ios swift

我在使用此 UIImageView 扩展正确缓存 JSON 图像时遇到问题。当我第一次打开应用程序并向下滚动页面时,图像加载正确。然而,当我向上滚动时,它们不会重新加载并且完全消失。任何人都可以看到代码有什么问题吗?

   let imageCache = NSCache<AnyObject, AnyObject>()

   extension UIImageView   {

    func loadImageUsingUrlString(urlString: String) {
        let url = NSURL(string: urlString)

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

        URLSession.shared.dataTask(with: url! as URL) { (data, response, error) in

            if error != nil {
                print(error ?? "URLSession error")
                return
            }

            DispatchQueue.main.async {

                let imageToCache = UIImage(data: data!)

                imageCache.setObject(imageToCache!, forKey: urlString as AnyObject)

                self.image = imageToCache
            }
        }.resume()
    }
}

这是 cell.swift 文件中的片段

let imageCache = NSCache<AnyObject, AnyObject>()

func setupThumbnailImage() {
    if let thumbnailImageUrl = television?.poster_url   {

        let urlPrefix = "https://www.what-song.com"
        let urlSuffix = thumbnailImageUrl

        let urlCombined = urlPrefix + urlSuffix

        thumbnailImageView.loadImageUsingUrlString(urlString: urlCombined)

    }
}

最佳答案

我建议使用kingFisher,它非常易于使用,并且它管理从缓存线程等开始的所有操作。

           let imageResource = ImageResource(downloadURL:URL(string: imagePath )!,cacheKey: imagePath )
           viewImage.kf.indicatorType = .activity
           viewImage.kf.setImage(with: resource)

其中imagePath是你的图片的url,viewImage是你的imageView

关于ios - Swift 图像缓存不重新加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47219755/

相关文章:

ios - 在 Xcode 4.2 上,应用程序总是在调试器中暂停

ios - 如何从 Alamofire 返回值

swift - 从 NSView 生成多页 PDF

function - Swift 中无效的函数重新声明

ios - UITableView 自定义单元格在滚动时复制 UIButton

ios - TabBar 覆盖导航堆栈中的 View Controller 内容

ios - Coredata 中的 child 数

ios - 使用自动布局和 systemLayoutSizeFittingSize

ios swift : Remove duplicates in an array of images

html - ios safari emoji 字体大小错误(无法放大)