Why is my swift code executing out of order? Firebase authentication

Viewed 70

I am calling Authenticator.loginUser() with the expectation that the method will log in a user then call getCurrentUser(). Based on printed output, getCurrentUser() is executing first. Is there a way to force it to execute in order?

class Authenticator: ObservableObject {
        
        @Published var currentUser: UserProfile = UserProfile()
        @Published var user: String = ""
        @Published var documentId: String = ""
            
        func loginUser (email: String, password: String, viewModel: UsersViewModel) {
            FirebaseAuth.Auth.auth().signIn(withEmail: email, password: password, completion: { result, error in
                
                guard error == nil else {
                    print ("error: \(error!)")
                    return
                }
                print ("user signed in")
            })
            self.user = self.getCurrentUser(viewModel: viewModel)
        }
        
        func getCurrentUser(viewModel: UsersViewModel) -> String {
            guard let userID = Auth.auth().currentUser?.uid else {
                return ""
            }
            
            viewModel.users.forEach { i in
                if (i.userId == userID) {
                    currentUser = i
                }
            }
            
            documentId = currentUser.documentId!
            print("auth.documentId \(documentId)")
            return userID
        }
        
    }
1 Answers

FirebaseAuth.Auth.auth().signIn is asynchronous - it runs in the background and not on the main thread. This means that signIn will be called some time in the future.

A solution is to put the call to getCurrentUser in the completion block:

func loginUser(email: String, password: String, viewModel: UsersViewModel) {
    FirebaseAuth.Auth.auth().signIn(withEmail: email, password: password, completion: { result, error in
        guard error == nil else {
            print("error: \(error!)")
            return
        }
        print("user signed in")
        self.user = self.getCurrentUser(viewModel: viewModel) // move here
    })
}
Related