我需要AlamofireImages的一点帮助。在应用程序中,点击表格视图单元格将使用内置的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扩展,而是使用Downloader。我不确定如何让Downloader: 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
}
}
}
如果有人知道如何完成这个或任何有用的提示或技巧,那将是伟大的!谢谢!