Because the user is still logged.
The first step is logout, you can do it in appDelegate inside applicationDidEnterBackground function. Just call this:
try! FIRAuth.auth()!.signOut()
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
try! FIRAuth.auth()!.signOut()
}
The second step is to do a new login ( if the user allowed to save the email and password in... userDefault.... for example) and get the new information about the login of the user inside applicationDidBecomeActive function.
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
// Check if the User data exist
let User = UserDefaults.standard
guard let myEmail = User.object(forKey: "userName") as? String else {
print("No User")
return
}
//Check if the user wants the automatic access
guard User.object(forKey: "automaticLogIn") as! Bool else {
print("Automatic LogIn disable")
return
}
// Now you can to do the automatic login
let password = User.object(forKey: "password") as! String
FIRAuth.auth()?.signIn(withEmail: myEmail, password: password, completion: { (user, error) in
if error == nil{
print("logIn succesfull")
}else{
let typeError = FIRAuthErrorCode(rawValue: error!._code)!
switch typeError {
case .errorCodeUserNotFound:
print("user not found")
case .errorCodeWrongPassword:
print("wrong password")
default:
break
}
}
})
}
And now you can call FIRAuth.auth()!.addStateDidChangeListener(), where you want, for example in viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
// Save the user data inside userDefault, you can do it where you want.... like a form inside an alertView
let User = UserDefaults.standard
User.set("userEmail...", forKey: "userName")
User.set("UserPassword", forKey: "password")
User.set(true, forKey: "automaticLogIn")
FIRAuth.auth()!.addStateDidChangeListener() { auth, user in
if user != nil {
// User is signed in.
print("start login success: " + (user?.email)! )
//self.performSegue(withIdentifier: loginToList, sender: nil)
} else {
// No user is signed in.
print("No user is signed in.")
}
}
}