如何快速将多个图像从 URL 保存到本地存储?

时间:2021-07-16 15:04:47

标签: swift userdefaults network-connection

我正在开发餐厅应用。 有 340 种食品数据。 我从用 Laravel 开发的后端获取这些数据。 应用程序在线运行良好。 但是,虽然网络关闭,所有食物数据都应该显示在应用程序中。 因此,我尝试将食物数据保存到本地。 最好将文本数据保存到本地(确切地说是 UserDefaults 和 FileSystem)。 但是,当我尝试从 url 将图像保存到本地时,发生错误并且没有完全保存到本地。

你见过这样的问题吗? 如果是,我感谢您的帮助。 谢谢

2 个答案:

答案 0 :(得分:0)

我不知道您遇到了什么错误,但我认为链接的答案可以帮助您。

此外,图像数据最好缓存。
如果您基于 System.ServiceModel 进行通信,则可以按如下方式处理缓存。

  • 将图像保存到缓存

    URLSession

  • 调出缓存图像

    Cache.imageCache.setObject(image, forKey: url.absoluteString as NSString)

代码

let cacheImage = Cache.imageCache.object(forKey: url.absoluteString as NSString)

为了使缓存更方便,请使用名为 class Cache { static let imageCache = NSCache<NSString, UIImage>() } extension UIImageView { func imageDownload(url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFit) { if let cacheImage = Cache.imageCache.object(forKey: url.absoluteString as NSString) { DispatchQueue.main.async() { [weak self] in self?.contentMode = mode self?.image = cacheImage } } else { var request = URLRequest(url: url) request.httpMethod = "GET" URLSession.shared.dataTask(with: request) { data, response, error in guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200, let mimeType = response?.mimeType, mimeType.hasPrefix("image"), let data = data, error == nil, let image = UIImage(data: data) else { print("Download image fail : \(url)") return } DispatchQueue.main.async() { [weak self] in print("Download image success \(url)") Cache.imageCache.setObject(image, forKey: url.absoluteString as NSString) self?.contentMode = mode self?.image = image } }.resume() } } } 的库。

答案 1 :(得分:0)

需要管理延迟加载,可以使用SDWebImages代替手动管理

SDWebImages 将自动管理您的图像缓存,并在没有互联网的情况下加载它们,这是它的一个简单用法

在 podfile 中添加 pod

pod 'SDWebImage'

用法:

import SDWebImage

imageView.sd_setImage(with: URL(string: "http://www.example.com/path/to/image.jpg"), placeholderImage: UIImage(named: "placeholder.png"))