How to check if user has valid Auth Session Firebase iOS?

前端 未结 7 2250
生来不讨喜
生来不讨喜 2021-02-19 04:53

I wanna check if the user has still a valid session, before I present the Home View controller of my app. I use the latest Firebase API. I think if I use the legacy, I\'ll be ab

7条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-19 05:36

    Updated answer

    Solution for latest Firebase SDK - DOCS

        // save a ref to the handler
        private var authListener: AuthStateDidChangeListenerHandle?
    
        // Check for auth status some where
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
    
            authListener = Auth.auth().addStateDidChangeListener { (auth, user) in
    
                if let user = user {
                    // User is signed in
                    // let the user in?
    
                    if user.isEmailVerified {
                        // Optional - check if the user verified their email too
                        // let the user in?
                    }
                } else {
                    // No user
                }
            }
        }
    
        // Remove the listener once it's no longer needed
        deinit {
            if let listener = authListener {
                Auth.auth().removeStateDidChangeListener(authListener)
            }
        }
    

    Original solution

    Solution in Swift 3

    override func viewDidLoad() {
        super.viewDidLoad()
    
        FIRAuth.auth()!.addStateDidChangeListener() { auth, user in
            if user != nil {
                self.switchStoryboard()
            }
        }
    }
    

    Where switchStoryboard() is

    func switchStoryboard() {
        let storyboard = UIStoryboard(name: "NameOfStoryboard", bundle: nil)
        let controller = storyboard.instantiateViewController(withIdentifier: "ViewControllerName") as UIViewController
    
        self.present(controller, animated: true, completion: nil)
    }
    

    Source

提交回复
热议问题