Search code examples
swiftfirebasefirebase-authentication

Swift – Authenticate and simultaneously fetch user Id from Firebase


Very new to Swift and just following some tutorials

I have a loginViewViewModel with a function to login a user.

However, I also want to grab the uid from Firebase after .signIn and print to the console. I plan to use this uid for other purposes but want to be sure I can first successfully print it to the console

Below is my loginViewViewModel and login function

class LoginViewViewModel: ObservableObject {
    @Published var email = ""
    @Published var password = ""

    init() {}
        
    func login(){
        // try to log in
        Auth.auth().signIn(withEmail: email, password: password)
        
        // fetch user id
        guard let userId = Auth.auth().currentUser?.uid else { return }
        print("Logging firebase user \(userId)")
    
    }
}

I build my app but nothing prints to the console after successful login.

What am I doing wrong?


Solution

  • So I think the issue here is that when you call Auth.auth().signIn this is requesting firebase to authenticate a user with the given credentials, and until firebase has sent back a result the Auth.auth().currentUser will be nil

    Firebase docs have this example.

    Auth.auth().signIn(withEmail: email, password: password) { [weak self] authResult, error in
      guard let strongSelf = self else { return }
      // ...
    }
    

    If you move your print statement inside that closure (and the provided credentials are correct) then that should solve your issue. Within this closure you are also given an authResult and an error you should use this to handle failed logins etc.

    In summary should look like this:

    Auth.auth().signIn(withEmail: email, password: password) { [weak self] authResult, error in
      guard let self = self else { return }
    
      guard let userId = Auth.auth().currentUser?.uid else { return }
      print("Logging firebase user \(userId)")
    }