Instead of creating a new anonymous user immediately when user
is nil
, introduce a short delay (e.g., 1-2 seconds). If Firebase restores the user in that time, skip creating a new user.
func StackOverFlow_forAuthState_GetOnAppLaunch() {
guard handle == nil else { return } // Ensure observer is only set once
handle = Auth.auth().addStateDidChangeListener({ (auth, user) in
if let user = user {
if user.isAnonymous {
print("🔥 - user is anonymous ⬜️ \(user.uid)")
} else if user.isEmailVerified {
print("🔥 - user is email verified ✅ \(user.uid)")
} else {
print("🔥 - user needs email verification 🟧 \(user.uid)")
}
} else {
print("🔥 - user not found. Waiting before signing in anonymously...")
// Delay before creating a new anonymous account
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
if Auth.auth().currentUser == nil { // Double-check before signing in
print("🔥 - Still no user, signing in anonymously...")
Auth.auth().signInAnonymously { (authResult, error) in
if let error = error {
print("❌ Error signing in anonymously: \(error.localizedDescription)")
return
}
guard let user = authResult?.user else { return }
print("✅ Anonymous UID: \(user.uid)")
}
} else {
print("✅ - Firebase restored user, no need to sign in again")
}
}
}
// Notify UI
NotificationCenter.default.post(name: .auth_change, object: nil)
})
}