Проблема с кешированием изображений с пользовательской ячейкой представления коллекции с помощью KingFisher

Я использую Kingfisher для кеширования изображения, хранящегося в Firebase. Я получаю изображение с помощью URL-адреса Firebase, а затем пытаюсь кэшировать это изображение для повторного использования. Приведенная ниже логика в configureCell(with video:Video) ранее была в cellForItemAt, и кеширование изображений работало нормально. Однако после перемещения этой логики в пользовательскую ячейку и вызова этой функции из cellForItemAt изображения не извлекаются через кеш. Каждое изображение загружается, а затем загружается повторно, если оно снова появляется в представлении коллекции. Мой код ниже. Спасибо за помощь заранее.

class ProminentVideoCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!

func configureCell(with video:Video) {
    self.timeLabel.text = video.date?.getElapsedInterval()
    let thumbnailImageView = UIImageView()
    ImageCache.default.retrieveImage(forKey: video.thumbnailurl!, options: nil) {
        image, cacheType in
        if let image = image {
            //Video thumbnail exists in cache--set it
            thumbnailImageView.image = image
            self.backgroundView = thumbnailImageView
            print("Get image \(image), cacheType: \(cacheType).")

        } else {
            //Video thumbnail does NOT exist in cache, download it
            video.downloadThumbnailFromStorage(with: { (url) in
                let resource = ImageResource(downloadURL: url, cacheKey: video.thumbnailurl!)
                let processor = BlurImageProcessor(blurRadius: 40.0) >> RoundCornerImageProcessor(cornerRadius: 20)

                thumbnailImageView.kf.setImage(with: resource, options: [.processor(processor)])
                self.backgroundView = thumbnailImageView
            })


        }
    }
}

В моем контроллере просмотра:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let currentVideo = self.selectedVideosArray.object(at: indexPath.row) as! Video
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ProminentVideoCollectionViewCell
        cell.configureCell(with: currentVideo)
        return cell
}

person joe    schedule 06.07.2017    source источник


Ответы (1)


Я добавил приведенный ниже код, чтобы убедиться, что механизм кеширования работает. Не совсем уверен, почему thumbnailImageView.kf.setImage не кэшировал изображения, но добавление приведенного ниже кода помогло.

//Video thumbnail does NOT exist in cache, download it
            video.downloadThumbnailFromStorage(with: { (url) in
                let resource = ImageResource(downloadURL: url, cacheKey: video.thumbnailurl!)
                let processor = BlurImageProcessor(blurRadius: 40.0) >> RoundCornerImageProcessor(cornerRadius: 20)

                thumbnailImageView.kf.setImage(with: resource, options: [.processor(processor)], completionHandler: { (image, error, cacheType, url) in
                    ImageCache.default.store(image!, forKey: video.thumbnailurl!)
                    self.backgroundView = thumbnailImageView
                })
            })
person joe    schedule 06.07.2017