我使用Firebase来处理我的用户注册并登录我的应用。但是如果我登录,然后完全关闭我的应用程序 - 用户被迫重新登录。我想让用户保持登录状态,除非他们点击"退出"
我的登录代码是:
Auth.auth().signIn(withEmail: email, password: password, completion: {(user, error) in
if let firebaseError = error {
print(firebaseError.localizedDescription)
return
}
self.presentTabBar()
})
}
}
除非明确告知退出,否则如何让该用户登录?
答案 0 :(得分:2)
这是2020年的一个完整示例:
在iOS + Firebase应用中的任何地方,您都可以简单地说:
guard let uid = Auth.auth().currentUser?.uid else {
return print("no current user!")
}
因此,在应用程序的启动屏幕上,只需:
import UIKit
import Firebase
import FirebaseUI
class ViewController: UIViewController, FUIAuthDelegate {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
guard let uid = Auth.auth().currentUser?.uid else {
return print("no current user, hence AuthUI flow...")
basicAuthUIFlow()
}
print("User .. \(Auth.auth().currentUser?.displayName)")
continueWhenUserPresent()
}
就这么简单。所以像往常一样...
private func basicAuthUIFlow() {
let authUI = FUIAuth.defaultAuthUI()
authUI?.delegate = self
let pp: [FUIAuthProvider] = [ FUIGoogleAuth() ]
authUI?.providers = pp
if let authVC = authUI?.authViewController() {
present(authVC, animated: true)
}
}
func authUI(_ authUI: FUIAuth,
didSignInWith authDataResult: AuthDataResult?,url: URL?, error: Error?) {
let u = authDataResult?.user
print("Successful login via authUI \(String(describing: u?.displayName))")
continueWhenUserPresent()
}
private func continueWhenUserPresent() {
.. pushViewController .. your first screen
}
答案 1 :(得分:1)
检查用户是否已登录:
if Auth.auth().currentUser != nil {
// User is signed in.
// ...
} else {
// No user is signed in.
// ...
}
如果用户已登录,则转到主页ViewController
。这样当他再次打开应用程序时,他将转到主页ViewController
,除非他退出FIRAuth.auth().signOut()
有关详情,请查看:https://firebase.google.com/docs/auth/ios/manage-users
答案 2 :(得分:1)
要保持用户登录,您需要检查currentUser Auth会话,如果它不是nil,那么您可以将用户重定向到主屏幕。
致电" setRootViewController "来自 didFinishLaunchingWithOptions 的方法,就在FirebaseApp.configure()代码
之后Swift 4
func setRootViewController() {
if Auth.auth().currentUser != nil {
// Set Your home view controller Here as root View Controller
self.presentTabBar()
} else {
// Set you login view controller here as root view controller
}
}