-1

I am new to swift and currently working on an application where I need to download an image that I stored on firebase cloud storage. One issue I am having is that I try to download it using the code directly from the firebase documentation which you can see below.

// Create a reference to the file you want to download
let islandRef = storageRef.child("images/island.jpg")

// Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes)
islandRef.getData(maxSize: 1 * 1024 * 1024) { data, error in
  if let error = error {
    // Uh-oh, an error occurred!
  } else {
    // Data for "images/island.jpg" is returned
    let image = UIImage(data: data!)
  }
}

But as you can see that image property seems to get lost in that closure, but obviously I want to be able to use that image and set it to be the image property of an imageview in my app. I wanted to know what I could do to allow that image to persist outside of that call back function for .getData

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Wana_B3_Nerd
  • 613
  • 3
  • 7
  • 21

1 Answers1

0

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...

Picode
  • 1,140
  • 1
  • 6
  • 12
  • Oh this actually worked thanks! But supposed I wanted to return the UIImage(data: data!) out of that function, how could I do that? – Wana_B3_Nerd May 12 '20 at 00:51
  • well it will create reference cycle... and you are updating UI on NON MAIN THREAD ... – Jawad Ali May 12 '20 at 01:01
  • So is this answer not the correct way to do it? Or was your comment in regards to my comment – Wana_B3_Nerd May 12 '20 at 01:39
  • this answer contains reference cycle – Jawad Ali May 12 '20 at 02:38
  • @jawadAli While Apple does want you to update the UI on the main thread, what you may not know is that UI calls within Firebase closures are ALL called on the main thread, so no reference cycle is created. So this answer is good. – Jay May 12 '20 at 17:03
  • @Wana_B3_Nerd This answer is correct (although Ref, a var, should NOT be capitalized). To answer the question in you comment, if you want to work with Firebase data outside the closure, do NOT user 'return'. You need either assign that data to a class var to be used elsewhere or something more dynamic like a completion handler, which is what I would recommend. – Jay May 12 '20 at 17:04