Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auth state change listener being fired twice?

When my page loads I need to know whether the user is logged in and perform different tasks based on that. The first thing I do is check if the they are logged in, but for some reason the if statement to check that is being validated twice. Here is my code:

override func viewDidAppear(_ animated: Bool) {
    FIRAuth.auth()?.addStateDidChangeListener { auth, user in
        if let user = user {
           print("User is logged in")
        }

"User is logged in" gets printed out twice to the console when the page loads instead of just once. Am I doing something incorrectly?

like image 219
MarksCode Avatar asked Oct 25 '25 05:10

MarksCode


1 Answers

i faced same problem. and it is not for logged in . it can be faced flowing option https://firebase.google.com/docs/reference/android/com/google/firebase/auth/FirebaseAuth.AuthStateListener

  • Right after the listener has been registered
  • When a user is signed in
  • When the current user is signed out
  • When the current user changes
  • When there is a change in the current user's token

so just crate a flag then check that one . or check response nil or not

Try this way :

override func viewDidAppear(_ animated: Bool) {
    FIRAuth.auth()?.addStateDidChangeListener { auth, user in
        if let user = user {
            if user != nil {
               print("User is logged in")
           }
        }

Note : try to use both flag and check user =! nil

like image 164
Nazmul Hasan Avatar answered Oct 26 '25 19:10

Nazmul Hasan