简体   繁体   English

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

[英]How to save multi images from URLs to local storage in swift?

I am developing Restaurant app.我正在开发餐厅应用程序。 There are 340 foods data.有 340 种食品数据。 I am getting this data from backend that developed with Laravel.我从用 Laravel 开发的后端获取这些数据。 App is working well in online.应用程序在线运行良好。 But, although network is turned off, All foods data should be displayed in app.但是,虽然网络关闭,所有食物数据都应该显示在应用程序中。 So, I tried to save foods data to local.因此,我尝试将食物数据保存到本地。 It is good to save text data to local(exactly, UserDefaults and FileSystem).最好将文本数据保存到本地(确切地说是 UserDefaults 和 FileSystem)。 But, when I try to save images to local from urls, It occur error and don't save to local exactly.但是,当我尝试从 url 将图像保存到本地时,会发生错误并且没有完全保存到本地。

Have you ever seen such problems?你见过这样的问题吗? If yes, I appreciate your help.如果是,我感谢您的帮助。 Thanks谢谢

I don't know exactly what error you faced, but I think the answer to the link can help you.我不确切知道您遇到了什么错误,但我认为链接的答案可以帮助您。

Additionally, image data would be good to be cached.此外,图像数据最好缓存。
If you communicate based on URLSession , you can process caching as below.如果您基于URLSession通信,则可以按如下方式处理缓存。

  • Saving an Image to a Cache将图像保存到缓存

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

  • Bring up cached images调出缓存的图像

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

Code代码

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()
      }
   }
}

To make caching more convenient, use a library called Kingfisher .为了使缓存更方便,请使用名为Kingfisher的库。

You need to manage lazy loadings, you can use SDWebImages instead of manage it manually您需要管理延迟加载,您可以使用SDWebImages而不是手动管理它

SDWebImages will automatically manage your images caches and will also load them without internet here is a simple usage of it SDWebImages 将自动管理您的图像缓存,并在没有互联网的情况下加载它们,这是它的一个简单用法

add pod in podfile在 podfile 中添加 pod

pod 'SDWebImage'

usagae:用法:

import SDWebImage

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM