gpt4 book ai didi

ios - 将 AlamofireImage 响应缓存到磁盘

转载 作者:行者123 更新时间:2023-11-30 12:14:06 24 4
gpt4 key购买 nike

我需要一些有关 AlamofireImages 的帮助。在应用程序中,点击表格 View 单元格将使用内置的 ImageView 扩展下载并设置图像,如下所示:

func sendImageRequest(imageView: UIImageView, item: CatalogItem, isLargeImage: Bool? = false){
let imageURL = ImageManager.URLBuilder(sku: item.sku, largeImage: isLargeImage)

// Clear the image so that recycled images are cleared.
imageView.image = nil

// Create the request and add the token string to the authorization header
var urlRequest = try! URLRequest(url: URL(string: imageURL)!)
urlRequest.setValue("Bearer \(ImageManager.getTokenString()!)", forHTTPHeaderField: "Authorization")

// If the token exists AND is VALID (not expired) - Get the image.
if ImageManager.checkIfTokenExists() && ImageManager.checkTokenIsValid(){
debugPrint("Valid token already exists. Fetching image... TableViewExtension")
imageView.af_setImage(withURLRequest: urlRequest){ response in
switch response.result{
case .success(let image):
debugPrint(response)
debugPrint("SUCCESS")
break
case .failure(let error):
debugPrint("Error: \(error)")
debugPrint(response.response)
break
}
}
}
// Else if the token exists AND is INVALID (expired) - Delete the old token, get a new one, and fetch the image
else if ImageManager.checkIfTokenExists() && !ImageManager.checkTokenIsValid(){
debugPrint("Token expired... Getting new token.")
ImageManager.deleteToken()
let tokenRequest = NetRequest.newTokenRequest(url: "http://\(SettingsManager.KEY_ServerURL).ziizii.io/zz/jwt/new?service=images.ziizii.io")
tokenRequest.requestJWTToken(){
debugPrint("Token renewed. Fetching image...")
imageView.af_setImage(withURLRequest: urlRequest)
}
}
// If the token doesn't exist, request a new one and fetch the image.
else{
debugPrint("Requesting new token...")
let tokenRequest = NetRequest.newTokenRequest(url: "http://\(SettingsManager.KEY_ServerURL).ziizii.io/zz/jwt/new?service=images.ziizii.io")
tokenRequest.requestJWTToken(){
debugPrint("Token aquired. Fetching image...")
imageView.af_setImage(withURLRequest: urlRequest)
}
}
}

所以,这部分我没问题。它可以工作,它将对象缓存到磁盘并设置 ImageView 图像。如果您稍后再次点击它,它会检查图像是否在缓存中,如果是,则只需应用该图像。整洁。

现在,该项目的一个新要求是让用户能够预加载每个图像并缓存它们。现在我不再使用 AFI ImageView 扩展,而是使用下载器。我不确定如何让下载器:A)缓存到磁盘和B) 当用户点击单元格时,让 ImageView 扩展检查相同的缓存以查看它是否已预加载并应用该图像。

AFI 足够聪明,可以在发送请求之前检查图像数据的缓存,因此我确信这是可能的。

到目前为止我下载的图像如下:

static var downloader = ImageDownloader.default

static func downloadImage(urlRequest: URLRequestConvertible)
{
self.downloader.download(urlRequest) { response in
switch response.result{
case .success(let image): // If successful, cache the image.
print("SUCCESS")
break
case .failure(let error): // If unsuccessful, remove the cached 404 response and apply a nil image.
print("ERROR: \(response.error)")
break
}
}
}

如果有人知道如何实现此目的或任何有用的提示或技巧,那就太好了!谢谢!

最佳答案

好吧,我假设您正在从字符串中下载图像作为下载网址。我也处理过同样的问题;就我而言,我没有使用 Alamofire,我使用的是 ImageView 的扩展:

let imageCache = NSCache<AnyObject, AnyObject>()

扩展 UIImageView {

func downloadImage(from imgURL: String!) {

self.image = nil

// Check if there's an image in the cache

if let cachedImage = imageCache.object(forKey: imgURL as AnyObject) as? UIImage {
self.image = cachedImage
return
}

// Otherwise, download image from Firebase via URL-string

let url = URLRequest(url: URL(string: imgURL)!)

let task = URLSession.shared.dataTask(with: url) {
(data, response, error) in

if error != nil {
print(error!)
return
}

DispatchQueue.main.async {
if let image = UIImage(data: data!) {
imageCache.setObject(image, forKey: imgURL as AnyObject)
}
self.image = UIImage(data: data!)
}

}

task.resume()
}

}

现在我只需调用即可解决预加载问题

for i in objects { // whatever object you're having

imageView.downloadImage(fromURL: i.url)

}

...在 viewDidLoad() 中。

现在,它会循环遍历所有自定义对象,下载并缓存所有图像,如果用户点击图像,则会立即从缓存中加载该图像。我希望这能帮助您解决问题。

关于ios - 将 AlamofireImage 响应缓存到磁盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45636455/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com