如何在Swift中使用URLSession缓存图像

编程入门 行业动态 更新时间:2024-10-11 17:22:39
本文介绍了如何在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缓存图像

本文发布于:2023-11-26 04:29:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632629.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:缓存   图像   如何在   URLSession   Swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!