问题
I'm using firebase for login and I need to know how to stay logged in until I log out. I have heard about UserDeafults but I'm not sure on how to use it. Here is my login view controller:
import FirebaseAuth
import FirebaseFirestore
import Firebase
import FirebaseAnalytics
import UIKit
class LoginViewController: UIViewController {
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var errorLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setUpElements()
if Auth.auth().currentUser != nil {
// User is signed in.
DispatchQueue.main.async {
self.presentHomeViewController()
}
} else {
// No user is signed in.
}
}
func setUpElements() {
// Hide the error label
errorLabel.alpha = 0
// Style the elements
Utilities.styleTextField(emailTextField)
Utilities.styleTextField(passwordTextField)
Utilities.styleFilledButton(loginButton)
}
func presentHomeViewController() {
let homeViewController = self.storyboard?.instantiateViewController(identifier: Constants.Storyboard.homeViewController) as? ViewController
self.view.window?.rootViewController = homeViewController
self.view.window?.makeKeyAndVisible()
}
@IBAction func loginTapped(_ sender: Any) {
// TODO: Validate Text Fields
// Create cleaned versions of the text field
let email = emailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let password = passwordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
// Signing in the user
Auth.auth().signIn(withEmail: email, password: password) { (result, error) in
if error != nil {
// Couldn't sign in
self.errorLabel.text = error!.localizedDescription
self.errorLabel.alpha = 1
}
else {
self.presentHomeViewController()
}
}
}
}
回答1:
If you don't logOut
. User keeps at login
state. For check is logged in user exist
:
Auth.auth().addStateDidChangeListener { auth, user in
if user != nil{
//Logged in user exist.
}
}
This your segue id. Write whatever you want :
Edited for your code :
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setUpElements()
Auth.auth().addStateDidChangeListener { auth, user in
if user != nil{
// User is signed in.
print("User is not logged out.")
self.performSegue(withIdentifier: "yourSegueId", sender: nil)
} else {
// No user is signed in.
print("No user is signed in.")
}
}
}
Hope it helps...
来源:https://stackoverflow.com/questions/61229716/how-do-i-keep-a-user-logged-in-swift