How do I keep a user logged in? Swift

情到浓时终转凉″ 提交于 2021-02-15 06:23:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!