-->

Firebase retrieve image from URL save with Firebas

2020-08-03 03:27发布

问题:

I have saved an image to the Firebase storage and also saved the imageURL to Firebase database, but how can I get the image back by the URL saved in firebase database? Here is how I save it

func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
    userPhoto.image = image
    dismissViewControllerAnimated(true, completion: nil)
    var data = NSData()
    data = UIImageJPEGRepresentation(userPhoto.image!, 0.8)!
    // set upload path
    let filePath = "\(FIRAuth.auth()!.currentUser!.uid)/\("userPhoto")"
    let metaData = FIRStorageMetadata()
    metaData.contentType = "image/jpg"
    self.storageRef.child(filePath).putData(data, metadata: metaData){(metaData,error) in
        if let error = error {
            print(error.localizedDescription)
            return
        } else {
            // store downloadURL
            let downloadURL = metaData!.downloadURL()!.absoluteString
            // store downloadURL at database
            self.databaseRef.child("users").child(FIRAuth.auth()!.currentUser!.uid).updateChildValues(["userPhoto": downloadURL])
        }
    }
}

回答1:

Here's one way of doing it, by downloading the data and then creating a UIImage for it:

self.storage.referenceForURL(url).dataWithMaxSize(25 * 1024 * 1024, completion: { (data, error) -> Void in
    let image = UIImage(data: data!)
    chatMessage.image = image!
    self.messages.append(chatMessage)
    self.tableView.reloadData()
    self.scrollToBottom()
})

This code comes from the Zero To App talk at Google I/O. Complete code is available in this gist