我立即将窗口的 Root View Controller 设置为登录 Controller ,登录 Controller 检查来自 Firebase 的用户身份验证。如果用户登录, Controller 将 Root View Controller 更改为提要 Controller 。否则,登录 Controller 将自行处理。
class LoginController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let uid = Auth.auth().currentUser?.uid {
Database.database().reference().child("users").observeSingleEvent(of: .value, with: { snapshot in
if snapshot.hasChild(uid) {
AppDelegate.launchApplication()
}
else {
self.setUpUI()
}
})
}
else {
self.setUpUI()
}
}
...
}
launchApplication
在哪里
class func launchApplication() {
guard let window = UIApplication.shared.keyWindow else { return }
window.rootViewController = UINavigationController(rootViewController: FeedController())
}
除了 if let uid = Auth.auth().currentUser?.uid
,我还在检查 uid(如果不是 nil
)存在于我的数据库中,因为我遇到过已删除用户仍然不是 nil
的情况。
问题是在启动屏幕完成后,有一段时间登录 Controller 是可见的,尽管它是空白的。有时这一刻会持续几秒钟。我如何检查身份验证以使登录 Controller 完全不可见——以便应用程序决定如何在启动屏幕消失后立即继续?谢谢。
最佳答案
1) 如果您想从 app delegate 本身设置 rootController,请使用以下代码。如果您的 currentUser.uid 不为 nil 并与数据库中的值匹配,请使用检查,然后在 Appdelegate 的 DidFinishLaunchingWithOptions
中执行以下代码。我用过
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FirebaseApp.configure()
GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
if let uid = Auth.auth().currentUser?.uid {
Database.database().reference().child("users").child(uid).observeSingleEvent(of: .value, with: { snapshot in
if snapshot.exist() {
let storyBoard = UIStoryboard.init(name: "Main", bundle: nil)
let vc = storyBoard.instantiateViewController(withIdentifier: "feedController") as! FeedController
self.window?.rootViewController=vc
self.window?.makeKeyAndVisible()
}
else {
//Present your loginController here
}
})
}
return true
}
2) 方法:当您初始化登录 Controller 而不是从 Appdelegate 或 LaunchApplication 中的代码调用函数时。在login类中创建一个函数,当需要的参数匹配时,编写如下代码
var transition: UIViewAnimationOptions = .transitionFlipFromLeft
let rootviewcontroller: UIWindow = ((UIApplication.shared.delegate?.window)!)!
rootviewcontroller.rootViewController = self.storyboard?.instantiateViewController(withIdentifier: "rootnav")//rootnav is Storyboard id of my naviagtionController attached to the DestinationController [FeedController]
let mainwindow = (UIApplication.shared.delegate?.window!)!
mainwindow.backgroundColor = UIColor(hue: 0.6477, saturation: 0.6314, brightness: 0.6077, alpha: 0.8)
UIView.transition(with: mainwindow, duration: 0.55001, options: transition, animations: { () -> Void in
}) { (finished) -> Void in
}
关于ios - Swift Firebase 检查认证更顺畅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45316134/