Search code examples
iosswiftfirebaseuiimageviewgoogle-cloud-storage

StorageReference to URL


I am trying to follow Firebase's documentation on how to display a image from firebase Storage to the user in app. This is that documentation below:

// Reference to an image file in Firebase Storage
let reference = storageRef.child("images/stars.jpg")

// UIImageView in your ViewController
let imageView: UIImageView = self.imageView

// Placeholder image
let placeholderImage = UIImage(named: "placeholder.jpg")

// Load the image using SDWebImage
imageView.sd_setImage(with: reference, placeholderImage: placeholderImage)

I try to do this myself:

//get image url from deal
self.ref.child("deals").child("log").child(currentDealView).child("pictures").child(currentImageView).child("imageSelected").child("imageSelected").observeSingleEvent(of: .value) { (snapshot) in
    let imageUrlString = snapshot.value as! String
    let imageUrlUrl = URL(string: imageUrlString)

    print(imageUrlString)
    //prints "deals/log/dealNumber83/pictures/googleScreenshot/imageSelected"

    // Reference to an image file in Firebase Storage
    let reference = self.storageRef.child(imageUrlString)

    // UIImageView in your ViewController
    let viewPicImageView: UIImageView = self.viewPicImageView

    // Placeholder image
    let placeholderImage = UIImage(named: "placeholder.jpg")

    // Load the image using SDWebImage

    viewPicImageView.sd_setImage(with: reference, placeholderImage: placeholderImage)

but on the very last line I have a error at "with: reference," saying: "Cannot convert value of type 'StorageReference' to expected argument type 'URL?'" I can't find any info online on how to convert a StorageReference to a URL? Thanks.


Solution

  • You can use this :

    let Ref = Storage.storage().reference(forURL: imageUrlUrl)
    Ref.getData(maxSize: 1 * 1024 * 1024) { data, error in
        if error != nil {
            print("Error: Image could not download!")
        } else {
            yourImageView.image = UIImage(data: data!)
        }
    }
    

    Hope it helps...