How to Make a Function Complete Before Calling Others in an Ibaction

How can I make a function complete before calling others in an IBAction?

Something like this:

func verify(myText: String, completion: (bool: Bool)->()) {
var result = true
// some code that fetches a string "orlando" on the server
if myText == "orlando" {
result = false
}
completion(bool: result)
}

And you call it in your IBAction like this, with a trailing closure:

verify(myTextField.text!) { (bool) in
if bool {
// condition in `verify()` is true
} else {
// condition in `verify()` is false
}
}

Note: where you say "some code that fetches a string "orlando" on the server", be careful to not set the new completion after the async call, otherwise you would still experience the same issue... The completion should be used in the same scope as the async call result.

How to Auto call an @IBAction function

You can either change the signature of the IBAction by making its parameter an Optional like this:

@IBAction func doSomeTask(sender: UIButton?) {
// code
}

and then call it with nil as an argument:

doSomeTask(nil)

Or you can use the IBAction as a wrapper for the real function:

func doSomeTaskForButton() {
// ...
}

@IBAction func doSomeTask(sender: UIButton) {
doSomeTaskForButton()
}

meaning you can then call doSomeTaskForButton() from wherever you want.

How Can I Make Sure This Function Completes Before I Interpret The Response?

The problem in your code is the line here:

task.resume()
finished(apiResult)

You should remove the call to the finished completion handler, since that one should be called in the placed where it is already placed, after getting the response.

Another improvement suggestion to you would be to simplify your field validation code to use guard statements.

What's the best way to call an IBAction from with-in the code?

The proper way is either:

- [self functionToBeCalled:nil] 

To pass a nil sender, indicating that it wasn't called through the usual framework.

OR

- [self functionToBeCalled:self]

To pass yourself as the sender, which is also correct.

Which one to chose depends on what exactly the function does, and what it expects the sender to be.



Related Topics



Leave a reply



Submit