Кеш AlamofireImage не работает в моем приложении - PullRequest
0 голосов
/ 15 ноября 2018

Я использую af_setImage (), чтобы установить изображение для UIImageView.Мне нужно кэшировать изображение, и если оно кэшируется, я хочу, чтобы он не делал переход.Я пробовал некоторые коды ниже, но кэш изображений с идентификатором всегда возвращает ноль.Кажется, что 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)
                }
            }
        )
    }

В чем я не прав?

Заранее спасибо (´ ▽ `)

1 Ответ

0 голосов
/ 17 мая 2019

Я обнаружил, что основная проблема с 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, например, для отображения изображения внутри textView с помощью NSTextAttachment

...