如何让用户退出应用程序并返回,而不必登录Firebase

时间:2017-07-11 14:19:20

标签: swift xcode firebase

我试图让用户退出应用程序并返回,而不必一次又一次登录。我的下面的函数检查用户是否已登录,我在viewDidLoad()中运行此函数。我一直在阅读,看起来我必须使用Auth.auth()?.currentUser?而且!我不确定如何实施。

private func checkIfUserLoggedIn() {
    if Auth.auth().currentUser?.uid == nil {
        perform(#selector(handleLogout), with: nil, afterDelay: 0)

    } else {

        let uid = Auth.auth().currentUser?.uid
        Database.database().reference().child("users").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in

            if let dictonary = snapshot.value as? [String: AnyObject] {
                self.navigationItem.title = (dictonary["name"] as? String)
            }

        }, withCancel: nil)
    }
}

这是我在下面的登录代码

func handleLogin() {
        guard let email = emailTextField.text, let password = passwordTextField.text else {
            print("Form is not valid")
            return
        }
        Auth.auth().signIn(withEmail: email, password: password, completion: { (user, error) in

            if error != nil {
                print(error!)
                self.loginErrorAlert("Error!", message: "Username or password incorrect, please try again.")
                return
            }
            //successfully logged in our user
             self.performSegue(withIdentifier: "chatRoom", sender: self)
        })
    }
    func handleRegister() {
        guard let email = emailTextField.text, let password = passwordTextField.text, let name = nameTextField.text else {
            print("Form is not valid")
            signupErrorAlert("Error!", message: "Could not be Registered at this time, please try again.")
            return
        }
        Auth.auth().createUser(withEmail: email, password: password, completion: { (user: User?, error) in

            if error != nil {
                print(error!)
                self.loginErrorAlert("Error!", message: "Could not be Registered at this time, please try again later.")
                return
            }

            guard let uid = user?.uid else {
                return
            }
            //successfully authenticated user
            let ref = Database.database().reference(fromURL: "https://boccighub.firebaseio.com/")
            let usersReference = ref.child("users").child(uid)
            let values = ["name": name, "email": email]
            usersReference.updateChildValues(values, withCompletionBlock: { (err, ref) in

                if err != nil {
                    print(err!)
                    return
                }
                self.performSegue(withIdentifier: "chatRoom", sender: self)
            })
        })
    }

2 个答案:

答案 0 :(得分:0)

我更新了你的代码,我认为你的函数反向工作(当UID为零时处理注销)。如果正确,即使应用关闭,Firebase也会保存当前登录的用户。

private func userLoggedIn() -> Bool{
    if Auth.auth().currentUser?.uid == nil {
    return false
    }else{
    return true
    }
 }
override func viewDidLoad{
if userLoggedIn(){
// perform any action knowing the user is logged in
let uid = Auth.auth().currentUser!.uid
Database.database().reference().child("users").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
            if let dictonary = snapshot.value as? [String: AnyObject] {
                self.navigationItem.title = (dictonary["name"] as? String)
            }
        })
    }else{
    // perform any action knowing the user is not logged in
    perform(#selector(handleLogout), with: nil, afterDelay: 0)
   }
}

答案 1 :(得分:0)

你可以做的是在viewWillAppear中添加一个状态监听器,以便在加载视图之前检查它。

  var handle: FIRAuthStateDidChangeListenerHandle?

  override func viewWillAppear(_ animated: Bool) {
     handle = FIRAuth.auth()?.addStateDidChangeListener({ (auth, user) in
     if FIRAuth.auth()?.currentUser != nil{
      // go to main screen

      }else{

      // go to login screen
     }

    })

  }