Search code examples
iosswiftgoogle-cloud-firestorefirebase-storagekingfisher

Download image with Kingfisher from Firebase Storage


Inside my app I store images in Firebase Storage and also its url to Cloud Firestore. Now when I try to retrieve this image I am using Kingfisher but I think I have a misunderstanding of how Kingfisher works. This is my code:

let imageView = UIImageView()
    imageView.image = UIImage()
    if let imageUrl = URL(string: imageUrlString) {
        let resource = ImageResource(downloadURL: imageUrl)
        imageView.kf.setImage(with: resource) { (result) in
            switch result {
            case .success(_):
                print("success")
            case .failure(_):
                print("fail")
            }
        }
    }
dataSourceArrayWithWishes[wishIDX].wishes.append(image: imageView.image!)

What I would like to to here is if the imageUrl is correct, retrieve it and then save it to dataSourceArrayWithWishes as a UIImage. If not, then just save an empty UIImage.

However when a valid imageUrl is given, it fails because imageView.image! must not be null.

Can anyone help me out here?


Solution

  • Move it here inside success block

            case .success(_):
                print("success") 
               dataSourceArrayWithWishes[wishIDX].wishes.append(image: imageView.image!)
            case .failure(_):
                print("fail")
            }
        }
    }
    

    This imageView.kf.setImage(with: resource) { (result) in is an asynchnous method meaning that the line being crashed dataSourceArrayWithWishes[wishIDX].wishes.append(image: imageView.image!) runs before the image is fetched from firebase hence it's nil