Reputation: 2274
I have a problem in my app where I have a method called signUpButtonTapped
:
@objc func signUpButtonTapped(_ sender: Any) {
if !areFieldsValid()! {
// some error in textfield
theScrollView.scrollToTop()
}else { /* create user */ }
As you can see I call the method areFieldsValid()
which checks all my textFields
for a couple of things including wether not the username is taken or not:
//MARK: Validate Fields
func areFieldsValid() ->Bool? {
var isValid = true
// check if username is valid
checkUsername(field: usernameTextField.text!) { (success) in
if success == true {
// username is taken
print("Username is taken")
self.setupUsernameTextField()
self.checkUsernameImage.image = UIImage(named: "false")
self.checkUserNameLabel.text = "Benutzername ist bereits vergeben"
isValid = false
}
}
return isValid
}
The problem I have is that the user gets created even if the username is already taken and areFieldsValid
should actually return false
but the program still proceeds...
I guess it's because the data is still loading while the program proceeds? I have no idea on how to fix this issues so I am grateful for every help!
Upvotes: 0
Views: 72
Reputation: 4061
Your call to the network is asynchronous, that means it could finish anytime in the future. Asynchronous calls simply start running and return immediately, calling a completion block (in your case, with a success
boolean flag) when they finish.
In this case, your definition of areFieldsValid()
is not correct, since it's expecting to return the result of an asynchronous call (which returns immediately). Your validating function should have a completion closure to handle stuff, like this:
func validateFields(completion: @escaping (Bool) -> Void) {
checkUsername(field: usernameTextField.text!) { success in
if success {
// username is taken
print("Username is taken")
self.setupUsernameTextField()
self.checkUsernameImage.image = UIImage(named: "false")
self.checkUserNameLabel.text = "Benutzername ist bereits vergeben"
self.isValid = false
}
completion(success) // call the completion closure with the success status
}
}
So you would call it like this:
@objc func signUpButtonTapped(_ sender: Any) {
validateFields { areValid in
if areValid {
self.theScrollView.scrollToTop()
} else {
// create user
}
}
}
Upvotes: 1