I have a button and when I press it I´m calling an Async function:
func check(url : String){
let url = NSURL(string: url)
print("Checking")
dispatch_async(dispatch_get_main_queue(), {
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
if error == nil {
self.isWorking = true
}
else{
self.isWorking = false
}
}
}
task.resume()
})
}
So when I press my button I do the following:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!){
let web = segue.destinationViewController as! ViewController()
check(url)
dispatch_async(dispatch_get_main_queue(), {
if (isWorking){
// Do stuff
}
})
}
The problem is that isWorking is called before the check method is completed.
How can I make sure that check is completed before I make my check for isWorking?
You could use a "completion handler":
And you call it like this, with a trailing closure:
You can post a notification to a listener to perform the segue only when the task is complete with NSNotificationCenter.defaultCenter().postNotificationName("name", object: nil):
This way the code in customSegue func will only be executed when error == nil
This will do the job: