简体   繁体   中英

Firebase reference is 'variable not available' when downloading picture in Swift

Title says everything. I'm just unable to download an image from Firebase Storage dir. Here is the snippet of the code which calls the function for setting data and it also calls the function which tries to download the picture:

 for element in Dict {
            if let itemDict = element.value as? [String:AnyObject]{
                let name = itemDict["name"] as! String
                let price = itemDict["price"] as! Float
                let imageObject = itemDict["image"] as! NSDictionary
                let hash = imageObject["hash"] as! String
                let storageDir = imageObject["storageDir"] as! String
                let image:UIImage = self.downloadImageProductFromFirebase(append: hash)!
                let product = Product(name: name, image: image, imageName:hash, price: price, storageDir : storageDir)
                self.productList.append(product)
            }
        }
        print(Dict)
        self.myTable.reloadData()

And here is the code which tries to download the image:

func downloadImageProductFromFirebase(append:String) -> UIImage?{
    let gsReference = Storage.storage().reference(forURL: "gs://fridgeapp-3e2c6.appspot.com/productImages/productImages/" + append)
    var image : UIImage?

    gsReference.downloadURL(completion: { (url, error) in
        if error != nil {
            print(error.debugDescription)
            return
        }
        URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in

            if error != nil {
                print(error.debugDescription)
                return
            }
            guard let imageData = UIImage(data: data!) else { return }

            DispatchQueue.main.async {
                image = imageData
            }

        }).resume()
    })
    return image
}

But, for some reason, it crashes just when calling this last function, saying that "fatal error: unexpectedly found nil while unwrapping an Optional value". I tried to use the debugger, and I found out that Firebase reference to Storage variable says "variable not available".

Could someone of you guys help me with this? I think I read the Firebase doc about a hundred times, and still can't get the point.

Thank you!

Downloading an image from a remote server is an asynchronous task, that means that the result is not immediately available. This is the reason that gsReference.downloadURL accepts a completion callback as an argument, and has no return value.

Since your function ( downloadImageProductFromFirebase ) is simply a wrapper to gsReference.downloadURL , it should also accept a completion callback as an argument, and should not have a return value (ie remove the -> UIImage? ).

When you call self.downloadImageProductFromFirebase pass in a closure that receives the image, finds the index of the corresponding product in productList , and sets itself as the cell's image (assuming you're showing the image in the cell).

See this answer for how to asynchronously set cell images.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM