gpt4 book ai didi

swift - AlamofireImage 缓存在我的应用程序中不起作用

转载 作者:行者123 更新时间:2023-11-28 07:35:19 24 4
gpt4 key购买 nike

我正在使用 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)
}
}
)
}

我哪里错了?

提前谢谢你(´▽`)

最佳答案

我发现 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 中显示图像

关于swift - AlamofireImage 缓存在我的应用程序中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53315041/

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