繁体   English   中英

保持用户登录 swift

[英]Keep User Logged In in swift

我开发了应用程序,我首先使用登录系统打开 UIViewController,在 viewDidLoad 中我检查用户是否像这样登录(使用 firebase)

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .systemBackground

    if Auth.auth().currentUser == nil{
        let tap = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))
        view.addGestureRecognizer(tap)
            
        view.addSubview(logoImageView)
        logoImageView.center = CGPoint(x: horizontalCenter, y: verticalCenter/2.5)
            
        view.addSubview(emailTextField)
        emailTextField.center = CGPoint(x: horizontalCenter, y: verticalCenter)
            
        view.addSubview(passwordTextField)
        passwordTextField.center = CGPoint(x: horizontalCenter, y: verticalCenter+50)
            
        view.addSubview(loginButton)
        loginButton.center = CGPoint(x: horizontalCenter, y: verticalCenter+100)
            
        view.addSubview(dontHaveAccountButton)
        dontHaveAccountButton.center = CGPoint(x: horizontalCenter, y: verticalCenter*1.8)
            
        view.addSubview(showPasswordButton)
        showPasswordButton.center = CGPoint(x: horizontalCenter+100, y: verticalCenter+50)
    }
    else {
        view.addSubview(LlogindButton)
        LlogindButton.center = CGPoint(x: horizontalCenter, y: verticalCenter+100)
    }
}

我的配置放克看起来像:

@objc func config(){
    let tabBarVC = UITabBarController()
    
    let vc1 = UINavigationController(rootViewController: feedViewController())
    let vc2 = LibraryViewController()
    let vc3 = UINavigationController(rootViewController: CreatorViewController())
    let vc4 = ProfileViewController()
    let vc5 = UINavigationController(rootViewController: SettingsViewController())
    
    vc1.title = "Feed"
    vc2.title = "Library"
    vc3.title = "Creator Studio"
    vc4.title = "Profile"
    vc5.title = "Settings"
    
    tabBarVC.setViewControllers([vc1, vc2, vc3, vc4, vc5], animated: false)
    
    guard let items = tabBarVC.tabBar.items else{
        return
    }
    
    let images = ["house", "book.fill", "paintpalette.fill", "person.circle", "gear"]
    
    for x in 0..<items.count{
        items[x].image = UIImage(systemName:  images[x])
    }
    
    tabBarVC.modalPresentationStyle = .fullScreen
    present(tabBarVC, animated: true)
}

所以,这是我的问题。 在配置 function 中,我正在显示UITabBarController()并且如果用户登录,我想从UITabBarController显示我的一个栏,而不是调用我的配置函数的按钮。 instagram 中提供了相同的逻辑,我需要类似的东西。

Firebase Authentication 自动保持用户的身份验证 state 并在应用程序重新启动时恢复它。 这要求它调用服务器(例如检查帐户是否已被暂停),这意味着它是一个异步操作,可能无法在您的if Auth.auth().currentUser == nil时完成if Auth.auth().currentUser == nil运行。

为确保您的应用程序在更改响应身份验证 state,请使用身份验证 state 侦听器,如获取当前用户的文档的第一个片段所示:

handle = Auth.auth().addStateDidChangeListener { auth, user in
  // ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM