Download images - Firebase

Hi,

I have a collectionview and I have to view images in the cells, so I download the images. But I want to download all the images even when the cells of the collectionview is not visible, therefore the user has not scrolled through the whole collectionview. I know in advance the number of images to download. I use Firebase. Code:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "StickerCell", for: indexPath) as! StickerCell
    if(self.stickerPack != nil){
        cell.sticker = stickerPack.stickers[indexPath.row]
    }else{
        var string = ""
        string = self.arrLinkImagesStickers[indexPath.row]
        self.downloadImages(folderPath: string, success: { (img) in
            DispatchQueue.main.async {
                self.imageArray?.insert(img, at: indexPath.row)
                cell.imageView.image = img
            }
        }) { (error) in
            print(error)
        }
    }
    return cell
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if(self.stickerPack != nil){
        return self.stickerPack.stickers.count
    }
    return numStickers
}


func downloadImages(folderPath:String,success:@escaping (_ image:UIImage)->(),failure:@escaping (_ error:Error)->()){
    let reference = Storage.storage().reference(withPath: folderPath)
    reference.getData(maxSize: (1 * 1024 * 1024)) { (data, error) in
        if let _error = error{
            print(_error)
            DispatchQueue.main.async {
                failure(_error)
            }
        } else {
            if let _data  = data {
                let myImage:UIImage! = UIImage(data: _data)
                DispatchQueue.main.async {
                    success(myImage)
                }
            }
        }
    }

}

How can I solve it?Thanks! :wink:

@jack7 Do you still have issues with this?

that would make app extremely slow… because every cell is being reuse… the cells you see in the screen are the cell that will be reuse for every image you download… or you can NSCache api to cache images that would work better

This topic was automatically closed after 166 days. New replies are no longer allowed.