我正在使用af_setImage()将图像设置为UIImageView。我需要缓存图像,如果要缓存,则不要过渡。 我在下面尝试了一些代码,但是带有标识符的图像缓存始终返回nil。似乎每次都会调用imageCache.add(),但它不会添加缓存。
let imageCache = AutoPurgingImageCache()
if let image = imageCache.image(withIdentifier: post.mainImage) {
cell.postImageView.image = image
} else {
cell.postImageView.af_setImage(
withURL: URL(string: post.mainImage)!,
placeholderImage: PostCellView.defaultImage,
imageTransition: .crossDissolve(0.5),
completion: { response in
if let image = response.result.value, response.result.isSuccess {
imageCache.add(image, withIdentifier: post.mainImage)
}
}
)
}
我怎么了?
预先感谢您(´▽`)
答案 0 :(得分:0)
我发现AutoPurgingImageCache的主要问题是新实例不继承先前对象的缓存,因此,如果将此代码放入viewDidLoad函数中,则缓存始终返回nil
所以我设法用一个静态对象来解决,这是代码
import UIKit
import AlamofireImage
class ViewController: UIViewController {
static let imageCache = AutoPurgingImageCache(
memoryCapacity: 900 * 1024 * 1024,
preferredMemoryUsageAfterPurge: 600 * 1024 * 1024)
override func viewDidLoad() {
super.viewDidLoad()
let image_url = Bundle.main.object(forInfoDictionaryKey: "IMAGE_URL") as! String
let name = "/someimage.jpg"
let url = URL(string: image_url + name)
let urlRequest = URLRequest(url: url!)
let img_from_cache = ViewController.imageCache.image( for: urlRequest, withIdentifier: name)
if img_from_cache != nil{
print("FROM CACHE!!")
imageView.image = img_from_cache
// self.setImageViewSize(img_from_cache!)
}else{
print("NOT FROM CACHE!!")
imageView.af_setImage(
withURL: url!,
placeholderImage: nil,
filter: AspectRatioScaledToWidthFilter(width: self.view.frame.size.width),
completion :{ (rs) in
ViewController.imageCache.add(self.imageView.image!, for: urlRequest, withIdentifier: name)
}
)
}
}
}
/// Scales an image to a specified width and proportional height.
public struct AspectRatioScaledToWidthFilter: ImageFilter {
/// The size of the filter.
public let width: CGFloat
/**
Initializes the `AspectRatioScaledToWidthFilter` instance with the given width.
- parameter width: The width.
- returns: The new `AspectRatioScaledToWidthFilter` instance.
*/
public init(width: CGFloat) {
self.width = width
}
/// The filter closure used to create the modified representation of the given image.
public var filter: (Image) -> Image {
return { image in
return image.af_imageScaled(to: CGSize(width: self.width, height: self.width * image.size.height / image.size.width))
}
}
}
请注意,af_setImage函数已经使用了缓存,因此您必须将缓存对象用于其他目的,而不是在UIImage对象内显示图像,例如,在带有NSTextAttachment的textView内显示图像