如何在 Swift 4 中使用 SDWebImage 缓存从 firebase 存储中获取的图像数组?

How to cache an array of Images fetched from firebase Storage using SDWebImage in Swift 4?

我正在以数据的形式从 firebase 存储中获取图像,我想使用 SDWebImage 将图像缓存在我的应用程序中。请指导我如何实现它?

 for x in images_list{

                let storageRef = storage.child("images/\(x).jpg")
                storageRef.getData(maxSize: 1 * 1024 * 1024) { (data, error) in
                    if let error = error{
                        print(error.localizedDescription)
                        return
                    }
                    else{
                        imagesarray.append(UIImage(data: data!)!)
                    }
                    if let x = images_list.last{
                                cell.imageDemo.animationImages = imagesarray
                                cell.imageDemo.sd_setImage(with: storageRef) // Here I Want to cache the images of **imagesarray** that are being animated
                                cell.imageDemo.animationDuration = 2
                                cell.imageDemo.startAnimating()

                    }
                }


            }

您在问题中直接从 firebase 下载 imageData。您将需要使用 downloadURL 方法,而不是使用 getData。像这样:

for x in image_list {

        let storageRef = storage.child("images/\(x).jpg")

        //then instead of downloading data download the corresponding URL
        storageRef.downloadURL { url, error in
            if let error = error {

            } else {

                //make your imageArray to hold URL rather then images directly
                imagesArray.append(url)
            }
        }

    }

    //////This is were you would use those url////////
    let url = imageArray.first!
    imageView.sd_setImage(with: url, completed: nil)

这里最重要的部分是下载 url 而不是图像数据。每当您将图像 url 设置为 imageView 时,SDWebImage 库将缓存它并在已缓存时显示

我使用了 downloadURL 方法并缓存了图像数组,而不是 getData 方法。

var imagesarray = [URL]()
for x in images_list{
        let storageRef = storage.child("images/\(x).jpg")
        storageRef.downloadURL { (url, error) in
            if let error = error{
                print(error.localizedDescription)
            }
            else{
                imagesarray.append(url!)
            }
            if let x = images_list.last{
                cell.imageDemo.sd_setAnimationImages(with: imagesarray)
                cell.imageDemo.animationDuration = 2
                cell.imageDemo.startAnimating()
            }
        }
    }