5

I am just starting to learn IOS development, coming from the backend world. Im looking to pass in a userID to this function and return the name, all data coming from Firebase. My current attempt at breaking the name value out of the closure is not working, the empty string is returned. How do I go about structuring this code to get that 'name' variable to return.

    func getNameOfUser(uid: String) -> String {
    var name: String = ""
    FIRAuth.auth()?.signInAnonymouslyWithCompletion() { (user, error) in
        self.ref = FIRDatabase.database().reference()
        self.ref!.child("users").child(uid).child("name").observeSingleEventOfType(.Value, withBlock: { (snapshot) in
            name = snapshot.value! as! String
        }) { (error) in
            print(error.localizedDescription)
        }
    }
    return name
}
Evan Cathcart
  • 635
  • 2
  • 10
  • 13

1 Answers1

2

This cannot work. signInAnonymouslyWithCompletion() is working in background.

Asynchronously creates and becomes an anonymous user.

This means that getNameOfUser() and its local variable is already gone, when the completion block is executed.

func getNameOfUser(uid: String) -> String 
{
  var name: String = ""
  FIRAuth.auth()?.signInAnonymouslyWithCompletion() 
  { (user, error) in
  // Executed somewhere in the future
  }
// Executed immeditaly.
return name
}

Instead of returning the result, you should pass a completion block as argument to the function and execute that inside the completion block.

Amin Negm-Awad
  • 16,582
  • 3
  • 35
  • 50