Swift 4-如何使用缓存加载图像?

时间:2018-07-15 23:16:04

标签: swift image url caching uiimageview

我有UIImageView,我想在缓存中下载图像(如果存在),我使用了扩展功能。

我有此代码,但无法正常工作:

extension UIImageView {
    func loadImageUsingCache (_ urlString : String) {
        let imageCache = NSCache<AnyObject, AnyObject>()
        if let cachedImage = imageCache.object(forKey: urlString as AnyObject) {
            self.image = cachedImage as? UIImage
            return
        }
        let url = URL(string: urlString)
        URLSession.shared.dataTask(with: url!) { (data, response, error) in
            if data != nil {
                if let image = UIImage(data: data!) {
                    imageCache.setObject(image, forKey: urlString as AnyObject)
                    DispatchQueue.main.async(execute: {
                        self.image = image
                    })
                }
            }
        }.resume()
    }
}

2 个答案:

答案 0 :(得分:0)

您正在为每个图像创建新的NSCache对象,而不保留它。 您应该创建对象变量而不是本地变量。在这种情况下,它将无法扩展。您也可以尝试改用URLCache.shared。

答案 1 :(得分:0)

//这是完美的解决方案//

var imageCache =字符串:UIImage

CustomImageView类:UIImageView {

var lastImgUrlUsedToLoadImage: String?

func loadImage(with urlString: String) {

    // set image to nil
    self.image = nil

    // set lastImgUrlUsedToLoadImage
    lastImgUrlUsedToLoadImage = urlString

    // check if image exists in cache
    if let cachedImage = imageCache[urlString] {
        self.image = cachedImage
        return
    }

    // url for image location
    guard let url = URL(string: urlString) else { return }

    // fetch contents of URL
    URLSession.shared.dataTask(with: url) { (data, response, error) in

        // handle error
        if let error = error {
            print("Failed to load image with error", error.localizedDescription)
        }

        if self.lastImgUrlUsedToLoadImage != url.absoluteString {
            return
        }

        // image data
        guard let imageData = data else { return }

        // create image using image data
        let photoImage = UIImage(data: imageData)

        // set key and value for image cache
        imageCache[url.absoluteString] = photoImage

        // set image
        DispatchQueue.main.async {
            self.image = photoImage
        }
        }.resume()
}

}