Firebase登录后无法识别当前用户及登出注册新用户无UID问题
Hey David, let's break down your two Firebase Auth issues one by one:
There are a few common reasons this might happen, along with fixes:
You're checking
currentUserbefore the async login finishes
Firebase's login methods (likesignIn(withEmail:password:)) run asynchronously. If you try to grabAuth.auth().currentUserright after calling the login function, the network request hasn't completed yet, so the user state won't be updated. Always handle user logic inside the login completion closure, or use a state listener.You haven't set up an Auth state listener
Firebase recommends usingaddStateDidChangeListenerto track real-time user state changes (login, logout, token expiration, etc.). This is more reliable than checkingcurrentUsermanually. Here's how to implement it:Auth.auth().addStateDidChangeListener { auth, user in if let user = user { // User is signed in, handle your logic here print("Current user UID: \(user.uid)") } else { // No user is signed in print("No active user") } }Local cache glitches
Sometimes the local Auth cache can get out of sync. Try uninstalling and reinstalling your app, or clearing its stored data, then test login again.Incorrect project configuration
Double-check that yourGoogleService-Info.plistis properly added to your iOS project, and that the Bundle ID in your plist matches the one registered in the Firebase Console. Mismatched configs can break Auth state sync.
This is a classic async timing issue! Your code tries to grab currentUser immediately after calling createUser(withEmail:password:), but createUser runs asynchronously. The network request to create the user hasn't finished yet when you check currentUser, so it returns nil.
Fix: Move UID logic inside the createUser completion closure
Only when the completion closure fires do you know the user has been successfully created (and automatically signed in by Firebase). Here's your revised code:
guard let email = emailTextField.text, let password = passwordTextField.text else { print("Form is not valid") return } Auth.auth().createUser(withEmail: email, password: password) { authResult, error in if let error = error { print("Registration failed: \(error.localizedDescription)") return } // This is the safe place to access the new user's UID guard let uid = authResult?.user.uid else { print("No UID") return } print("Account creation successful, UID: \(uid)") }
Pro tip: Use authResult?.user directly instead of relying on currentUser here—it's the direct result of the registration request, so it avoids any potential state sync delays.
内容的提问来源于stack exchange,提问作者David Sung

