0

我对 Alamofire Image lib 有疑问。我尝试下载图像,然后终止应用程序并关闭 wifi。因此,当我在没有连接的情况下启动我的应用程序但我的图像没有出现时,我希望看到图像(第一次缓存在商店中)。

这是我在一个简单的 UIViewController 中的代码,其中包含一个 UIImage 和一个 UIButton ,它允许为某些测试刷新视图:

import UIKit
import AlamofireImage

class ViewController: UIViewController {

@IBOutlet weak var firstImage: UIImageView!
@IBOutlet weak var descriptionLabel: UILabel!

var imageCache: ImageRequestCache = AutoPurgingImageCache()
let urlRequest = URLRequest(url: URL(string: "https://httpbin.org/image/jpeg")!)

@IBAction func refreshView(_ sender: Any) {
    self.requestFirstImage()
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    self.requestFirstImage()
}

func requestFirstImage() {

    let downloader = self.diskImageDownloader()
    downloader.download(self.urlRequest) { response in
        if let image = response.result.value {
            self.firstImage.image = image
            // Add image to cache
            self.imageCache.add(image, for: self.urlRequest, withIdentifier: "wolf")
            self.descriptionLabel.text = "Image added to cache"
        }
    }

    // If image is stored in cache show it
    if let image = self.imageCache.image(for: self.urlRequest, withIdentifier: "wolf") {
        self.firstImage.image = image
        self.descriptionLabel.text = "Image showed from cache"
    } else {
        self.descriptionLabel.text = "Impossible to show image from cache"
        // call image from disk here
        ------> Here how read image which is located in alamofireimage_disk_cache subfolder of the app ?
    }

}

func diskImageDownloader(diskSpaceMB: Int = 300) -> ImageDownloader {

    let diskCapacity = diskSpaceMB * 1024 * 1024
    let diskCache = URLCache(memoryCapacity: diskCapacity, diskCapacity: diskCapacity, diskPath: "alamofireimage_disk_cache")
    let configuration = URLSessionConfiguration.default
    configuration.urlCache = diskCache
    let downloader = ImageDownloader(configuration: configuration)
    UIImageView.af_sharedImageDownloader = downloader

    return downloader
}   
}

预先感谢您的帮助。

亲切的问候,

4

1 回答 1

0

SDWebImage 成功了。当我第一次下载我的图像然后杀死我的应用程序时。如果之后我在没有 Internet 的情况下重新启动它,则会显示图像。

这里有一个例子:

import SDWebImage

@IBOutlet weak var myImage: UIImageView!            
let imageURL = URL(string:"Replace by url of image")

self.myImage.sd_setImage(with: imageURL!, placeholderImage:UIImage(named: "PlaceHolderImage")!)

供您参考,“PlaceHolderImage”是我在资产中的占位符图像的名称。所以换成你的。此图像将在下载图像之前/期间出现。

不要忘记安装 SDWebImage 库。在项目中使用此库的三种方法:

  • 使用 CocoaPods
  • 使用迦太基
  • 通过将项目克隆到您的存储库中

谢谢你,祝你好运。

于 2016-11-18T13:52:00.120 回答