我正在尝试为使用Facebook登录SDK的应用创建登录页面。加载RootViewController时,应确定用户是否已通过Facebook登录,如果已登录,则将其定向到应用程序的主页。否则,如果他们尚未通过Facebook登录,则应将其定向到登录页面进行登录。
我已经在RootViewController中添加了代码,用于检查currentUser是否为nil,但是无论用户是否通过Facebook登录,它似乎都可以重定向到首页。
import UIKit
import FirebaseAuth
class RootNavController: UINavigationController {
var handler: AuthStateDidChangeListenerHandle?
override func viewDidLoad() {
super.viewDidLoad()
self.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationBar.shadowImage = UIImage()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
handler = Auth.auth().addStateDidChangeListener({ (auth, user) in
self.checkLoggedInUserStatus()
})
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
guard let handler = handler else { return }
Auth.auth().removeStateDidChangeListener(handler)
}
fileprivate func checkLoggedInUserStatus() {
DispatchQueue.main.async {
if Auth.auth().currentUser == nil {
let controller = WelcomeController()
let navController = UINavigationController(rootViewController: controller)
self.present(navController, animated: true, completion: nil)
return
} else {
self.performSegue(withIdentifier: "UserLoggedIn", sender: nil)
return
}
}
}
仅当用户已经通过Facebook登录时,预期结果才会显示主页。
答案 0 :(得分:1)
除了快速更改之外,您的代码似乎还不错。只要您在再次打开应用程序之前注销用户,它就可以正常工作。请记住,Fb登录仅给您令牌以在Firebase中进行身份验证。之后,所有登录和注销都需要在Firebase中进行处理。我会这样更改您的代码。但主要是为了简单起见:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
handler = Auth.auth().addStateDidChangeListener({ (auth, user) in
if user != nil {
self.performSegue(withIdentifier: "UserLoggedIn", sender: nil)
} else {
let controller = WelcomeController()
let navController = UINavigationController(rootViewController: controller)
self.present(navController, animated: true, completion: nil)
}
})
}
如果在AppDelegate中完成所有这些操作,可能会更好。这样,您无需显示NavBar即可。相反,您可以仅在应用启动屏幕之后显示所需的屏幕。