如何检查用户是否具有有效的Auth Session Firebase iOS?

时间:2016-06-10 00:48:31

标签: ios swift firebase

在我展示应用程序的Home View控制器之前,我想检查用户是否仍然有效会话。我使用最新的Firebase API。我想如果我使用遗产,我就能知道这一点。

这是我到目前为止所做的:

我尝试像这样输入Xcode:

FIRApp().currentUser()
FIRUser().getCurrentUser()

但我似乎无法找到getCurrentUser函数。

7 个答案:

答案 0 :(得分:18)

if FIRAuth.auth().currentUser != nil {
   presentHome()
} else {
   //User Not logged in
}

更新SDK

if Auth.auth().currentUser != nil {

}

答案 1 :(得分:8)

Swift 3中的解决方案

override func viewDidLoad() {
    super.viewDidLoad()

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

switchStoryboard()

的位置
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

答案 2 :(得分:5)

if Auth.auth().currentUser?.uid != nil {

   //user is logged in

    }else{
     //user is not logged in
    }

答案 3 :(得分:4)

Swift 4中的解决方案

override func viewDidLoad() {
    super.viewDidLoad()
    setupLoadingControllerUI()
    checkIfUserIsSignedIn()
}

private func checkIfUserIsSignedIn() {

    Auth.auth().addStateDidChangeListener { (auth, user) in
        if user != nil {
            // user is signed in
            // go to feature controller 
        } else {
             // user is not signed in
             // go to login controller
        }
    }
}

答案 4 :(得分:2)

虽然您可以查看是否有Auth.auth().currentUser这样的用户,但这只会告诉您是否有已通过身份验证的用户,无论是否该用户帐户仍然存在或有效。


完整解决方案

真正的解决方案应该是使用Firebase的重新认证:

open func reauthenticate(with credential: AuthCredential, completion: UserProfileChangeCallback? = nil)

这可以确保(在应用程序启动时)先前登录/已通过身份验证的用户实际上仍然 可以并且可以通过Firebase进行身份验证。

let user = Auth.auth().currentUser    // Get the previously stored current user
var credential: AuthCredential

user?.reauthenticate(with: credential) { error in
  if let error = error {
    // An error happened.
  } else {
    // User re-authenticated.
  }
}

答案 5 :(得分:0)

override func viewDidLoad() {
FIRAuth.auth()!.addStateDidChangeListener() { auth, user in
            // 2
            if user != nil {
                let vc = self.storyboard?.instantiateViewController(withIdentifier: "Home")
                self.present(vc!, animated: true, completion: nil)
            }
        }
}

来源:https://www.raywenderlich.com/139322/firebase-tutorial-getting-started-2

答案 6 :(得分:0)

objective-c解决方案将是(iOS 11.4):

?flush=1