我对 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
}
}
预先感谢您的帮助。
亲切的问候,