Johnny  Hsieh Johnny Hsieh - 1 year ago 1688
Swift Question

Firebase retrieve image from URL save with Firebase database

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 {
} else {
// store downloadURL
let downloadURL = metaData!.downloadURL()!.absoluteString
// store downloadURL at database
self.databaseRef.child("users").child(FIRAuth.auth()!.currentUser!.uid).updateChildValues(["userPhoto": downloadURL])

Answer Source

Here's one way of doing it, by downloading the data and then creating a UIImage for it: * 1024 * 1024, completion: { (data, error) -> Void in
    let image = UIImage(data: data!)
    chatMessage.image = image!

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