我如何在应用程序中保持用户登录?迅捷 5 [英] How do i keep a user login in app ? swift 5

查看:37
本文介绍了我如何在应用程序中保持用户登录?迅捷 5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我制作了包含登录和注册功能的应用程序,该应用程序运行良好,但是当我关闭应用程序时,我无法让用户保持登录状态;它将用户返回到主视图控制器,用户必须在其中选择注册或登录.

Hello i have made app which include login and signup functionality which works fine but i am not able to keep user sign in when i close the app; it returns the user to the main view controller where a user will have to choose between sign up or log in.

有人可以帮忙吗?

这是我的代码:AppDelegate、登录、注册

Here is my code: AppDelegate, Login, SignUp

应用程序委托:

import UIKit
import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        sleep(2);
        FirebaseApp.configure()
        return true
    }
}

登录:

import UIKit
import Firebase
    
class LoginController: UIViewController {
    
    // MARK: - Properties
    @IBOutlet weak var passwordTextField: UITextField!
    @IBOutlet weak var login: UIButton!
    @IBOutlet weak var emailTextField: UILabel!
    
    var email = String()
    
    // MARK: - Init
    override func viewDidLoad() {
        super.viewDidLoad()
        emailTextField.text = email
    }
    
    // MARK: - Selectors
    
    @IBAction func loginButton(_ sender: UIButton) {
        
        guard let password = passwordTextField.text else {return}
        
        let finalPassword = password.trimmingCharacters(in: .whitespacesAndNewlines)
            
        //Password Validation and Alert
        if Utilities.isPasswordValid(finalPassword) == true {
            print("Password is Valid")
        } else {
            print("Password is not Valid")
            let myAlert = UIAlertController(title:"",message:"Please make sure your password is at least six characters, includes at least one number or special character, and is not a commonly used password.",preferredStyle:UIAlertController.Style.actionSheet)
            let okAction = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.destructive, handler: nil)
            myAlert.addAction(okAction)
            self.present(myAlert, animated: true, completion: nil)
        
            return
        }
        
        loginUserIn(withEmail: email, password: password)
     }
    
    // MARK: - API
    
    func loginUserIn(withEmail email:String, password: String) {
        
        Auth.auth().signIn(withEmail: email, password: password) { (result, error) in
        
        if let error = error {
            print("Failed to sign in", error.localizedDescription)
            return
        }
        print("Success Log In")
        
            UserDefaults.standard.set(true, forKey: "nil")
            UserDefaults.standard.synchronize()
    }
  }
}

注册:

import UIKit
import Firebase

class SignUpController: UIViewController {
    
    @IBOutlet weak var passwordTextField: UITextField!
    @IBOutlet weak var signUp: UIButton!
    @IBOutlet weak var emailText: UILabel!
    
    var email = String()
    
    // MARK: - Init
    
    override func viewDidLoad() {
        super.viewDidLoad()
        emailText.text = email
        signUp.addTarget(self, action: #selector(signUpButton), for: .touchUpInside)
    }

    // MARK: - Selectors
    
    @IBAction func signUpButton(_ sender: Any) {
    
    guard let password = passwordTextField.text,
                // use Swift's ability to infer the type here (and a couple other places)
                case let finalPassword = password.trimmingCharacters(in: .whitespacesAndNewlines),
                Utilities.isPasswordValid(finalPassword) else {
                // If we get here then either the password is null
                // or the password is not valid
                print("Password is not valid")

                // we need to display the alert, I'll move that into another function
                showPasswordInvalidAlert()

                return
            }

            // If we get here the password is valid
            print("Password is valid:", finalPassword)

        
        createUser(withEmail: email, password: password)
    }
        
    func showPasswordInvalidAlert() {
        // this is an alert not an action sheet
        let alert = UIAlertController(title: "", message: "Please make sure your password is at least six characters, includes at least one number or special character, and is not a commonly used password.", preferredStyle: .actionSheet)
        // this is not a destructive action
        let okAction = UIAlertAction(title: "Cancel", style: .destructive, handler: nil)
        alert.addAction(okAction)
        self.present(alert, animated: true, completion: nil)
    }
   
    // MARK: - API
    
    func createUser(withEmail email:String, password: String) {
        
        Auth.auth().createUser(withEmail: email, password: password) { (result, error) in
            
            if let error = error {
                print("Failed to sign up", error.localizedDescription)
                return
            }
            
            guard let uid = result?.user.uid else {return}
            
            let values = ["email": email]
            
            Database.database().reference().child("users").child(uid).updateChildValues(values, withCompletionBlock: { (error, ref) in
                
                if let error = error {
                    print("Falied to update", error.localizedDescription)
                    return
                }
                let mainStoryBoard = UIStoryboard(name: "Main", bundle: Bundle.main)
                
                guard let controller = mainStoryBoard.instantiateViewController(withIdentifier: "SubsViewController") as? SubsViewController else {
                    print("Error")
                    return
                }
                
                self.navigationController?.pushViewController(controller, animated: true)
                
               // self.present(controller, animated: true, completion: nil)
            
            })
        }
    }
}

推荐答案

  • 设置布尔检查.

    • set a boolean check.

      在登录时将其设置为 true.

      set it to true on logIn.

      在注销时将其设置为 false.

      set it as false on logout.

      在sceneDelegate上检查它的状态

      check its status on sceneDelegate

      根据存在的值加载视图控制器.

      load the viewcontroller according to the value present.

      let isLoggedIn = userdefaults.standard.bool(forKey: "loggedInValue")

      let isLoggedIn = userdefaults.standard.bool(forKey: "loggedInValue")

      if isLoggedIn == true{ 
       print("loggedIn")
      }else{
       print("loggedOut")
      }
      

    • 在你的场景委托集中

          func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
          // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
          // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
          // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
          let window = UIWindow(windowScene: scene as! UIWindowScene)
          // Assign window to SceneDelegate window property
          self.window = window
          
          if let loggedIn = UserDefaults.standard.bool(forKey: "IsUserLoggedIn") as? Bool{
              if loggedIn{
                  let initialViewController = storyboard.instantiateViewController(withIdentifier: "LoggedInScreen")
      
                  self.window?.rootViewController = initialViewController
              }else{
                  let initialViewController = storyboard.instantiateViewController(withIdentifier: "SignUpScreen")
                  self.window?.rootViewController = initialViewController
              }
          }else{
              let initialViewController = storyboard.instantiateViewController(withIdentifier: "SignUpScreen")
              self.window?.rootViewController = initialViewController
          }
          self.window?.makeKeyAndVisible()
          guard let _ = (scene as? UIWindowScene) else { return }
      }
      

      这篇关于我如何在应用程序中保持用户登录?迅捷 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆