简体   繁体   中英

Swift firebase createUser function completion block

I'm having a super weird issue when using firebase in swift. It seems that the script proceeds without waiting the completion block to finish. Here's what I mean:

I have a function:

func create_user(email:String, password:String) -> Bool{

    var create_suc = false

    Auth.auth().createUser(withEmail: email, password: password) { (user, error) in
        if let error = error{
            // Error creating new user.
            create_suc = false
            print("In fail closure: \(create_suc)")
        }else{
            // Create successfully.
            create_suc = true
            print("In success closure: \(create_suc)")
        }
    }
    print("Before return: \(create_suc)")
    return create_suc
}

And the context that calls this function:

 @IBAction func sign_up(_ sender: UIButton) {
        let result = create_user(email: acc_email.text!, password: acc_password.text!)

        print("Create successfully: \(result)")

The result I got is weird:

**Before return: false**
**Create successfully: false**
2018-08-26 16:41:55.313457-0700 chat_app[251:9301] TIC Read Status [2:0x0]: 1:57
2018-08-26 16:41:55.313611-0700 chat_app[251:9301] TIC Read Status [2:0x0]: 1:57
2018-08-26 16:41:56.013564-0700 chat_app[251:9300] TIC Read Status [3:0x0]: 1:57
2018-08-26 16:41:56.013721-0700 chat_app[251:9300] TIC Read Status [3:0x0]: 1:57
**In success closure: true**

It's not weird the task is asynchronous.

func create_user(email: String, password: String, completion: @escaping(_ res: Bool) -> Void ) {
  Auth.auth().createUser(withEmail: email, password: password) { (user, error) in
    if let error = error {
      // Error creating new user.
      completion(false)
      print("In fail closure: \(create_suc)")
    } else {
      // Create successfully.
      completion(true)
    }
  }
}

create_user(email: acc_email.text!, password: acc_password.text!) { (res) in
   print(res)
}

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