本文介绍了如何在 Swift 中使用 URLSession 缓存图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想增强以下代码以缓存图像,并且仅在之前未缓存的情况下才下载它们.我似乎找不到任何关于如何使用 URLSession 对象来做到这一点的好例子.
I would like to enhance the code below to cache images and only download them if they haven't been cached previously. I can't seem to find any good examples of how to use URLSession object to do this.
extension UIImageView { func loadImageWithURL(_ url: URL) -> URLSessionDownloadTask { let session = URLSession.shared let downloadTask = session.downloadTask(with: url, completionHandler: { [weak self] url, response, error in if error == nil, let url = url, let data = try? Data(contentsOf: url), let image = UIImage(data: data) { DispatchQueue.main.async { if let strongSelf = self { strongSelf.image = image } } } }) downloadTask.resume() return downloadTask } } 推荐答案已针对 Swift 4 更新
import UIKit let imageCache = NSCache<AnyObject, AnyObject>() class ImageLoader: UIImageView { var imageURL: URL? let activityIndicator = UIActivityIndicatorView() func loadImageWithUrl(_ url: URL) { // setup activityIndicator... activityIndicator.color = .darkGray addSubview(activityIndicator) activityIndicator.translatesAutoresizingMaskIntoConstraints = false activityIndicator.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true activityIndicator.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true imageURL = url image = nil activityIndicator.startAnimating() // retrieves image if already available in cache if let imageFromCache = imageCache.object(forKey: url as AnyObject) as? UIImage { self.image = imageFromCache activityIndicator.stopAnimating() return } // image does not available in cache.. so retrieving it from url... URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in if error != nil { print(error as Any) DispatchQueue.main.async(execute: { self.activityIndicator.stopAnimating() }) return } DispatchQueue.main.async(execute: { if let unwrappedData = data, let imageToCache = UIImage(data: unwrappedData) { if self.imageURL == url { self.image = imageToCache } imageCache.setObject(imageToCache, forKey: url as AnyObject) } self.activityIndicator.stopAnimating() }) }).resume() } }用法:
// assign ImageLoader class to your imageView class let yourImageView: ImageLoader = { let iv = ImageLoader() iv.frame = CGRect(x: 10, y: 100, width: 300, height: 300) iv.backgroundColor = UIColor(red: 0.94, green: 0.94, blue: 0.96, alpha: 1.0) iv.contentMode = .scaleAspectFill iv.clipsToBounds = true return iv }() // unwrapped url safely... if let strUrl = "picsum.photos/300/300".addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed), let imgUrl = URL(string: strUrl) { yourImageView.loadImageWithUrl(imgUrl) // call this line for getting image to yourImageView }更多推荐
如何在 Swift 中使用 URLSession 缓存图像
发布评论