简体   繁体   中英

How do I authenticate users in shoudPerformSegueWithIdentifier and Firebase?

I'm trying to create an authentication page in storyboard using IOS swift and Firebase. Here is my storyboardsegue declaration: 在此处输入图片说明

Then I'm using shouldPerformSegueWithIdentifier to authenticate it. However, I also what to log the user in Firebase so my code is like so:

override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {
if db.authData != nil {

  return true

} else {

  let email = emailTextField.text
  let password = passwordTextField.text

  db.authUser(email, password: password, withCompletionBlock: {
    error, authData in
    if error != nil {
      print(error.description)
    } else {
      print("logged in")
    }
  })

  return false
}

}

This code somewhat works but I would have to click the log in button twice because the first time logs in the user in Firebase, and the second time the db.authData is no longer nil because the user is already logged in so it returns true. I don't want to have to click twice to log in, I just want to click once. I can't just put return true or return false in the withCompletionBlock either because the block returns void. How do I make this work?

Using current implementation you can't achieve this feature. You have two ways to do this:

  1. Make the db.authUser() synchronous and return it's result
  2. Instead of connecting the login button segue to next screen, add an IBAction method and implement the method like

@IBAction func login(sender : AnyObject?)
{
   let email = emailTextField.text
   let password = passwordTextField.text

   db.authUser(email, password: password, withCompletionBlock: {
     error, authData in
       if error != nil
       {
          print(error.description)
       }
       else
       {
          // Navigate to next screen
          // Start perform segue here
       }
    })  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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