0

I have an function inside my app witch returns an image url from my firebase real-time database, but for some reason the value of url variable never change and returns the default value witch is none

My function:

func getImageURL() -> String {
    
    let ref: DatabaseReference = Database.database().reference()
    var url: String = "none"
    
    ref.child("users").child(Auth.auth().currentUser?.uid ?? "noid").observeSingleEvent(of: .value) { snapshot in
        
        url = snapshot.childSnapshot(forPath: "photoUrl").value as! String
        
    } withCancel: { error in
        print("ERROR: \(error.localizedDescription)")
    }
    
    return url
    
}
jnpdx
  • 45,847
  • 6
  • 64
  • 94
GSepetadelis
  • 272
  • 9
  • 24
  • 1
    Is `observeSingleEvent` asynchronous/a completion handler? If so, this might help: https://stackoverflow.com/a/68947022/14351818 – aheze Aug 27 '21 at 19:47
  • `url` is a local variable, so when you call, the function it is assigned "none" each time. In the closure it is assigned a new value but you don't do anything with it and then it is thrown away. You can't return a value from asynchronous code. You need to use a completion handler. – Paulw11 Aug 27 '21 at 21:55

0 Answers0