Darvish Kamalia
Darvish Kamalia

Reputation: 817

How do I check if dataTaskWithRequest is complete?

I'm new to iOS programming and trying to create my first app. I am fetching some data from a server using

  var task = NSURLSession.sharedSession().dataTaskWithRequest(request,

        completionHandler: { (data, response, error) -> Void in

I understand that all code in the completionHandler closure is executed when the task is completed. From my ViewController, I want to check if this task has been completed, and not load a table until it has. How do I check if this task has been completed?

I guess I could have the completionHandler set some global boolean variable to true when it runs, and I could check this variable in my ViewController, but I feel like there is a better way to do it with built in functionality, I just don't know it.

Upvotes: 3

Views: 3579

Answers (1)

Rob
Rob

Reputation: 437402

The view controller doesn't need to know when completionHandler is called. All you do is you have completionHandler actually dispatch a tableView.reload() back to the main queue (which then triggers the calling of the UITableViewDataSource methods). It's the completionHandler that initiates the UI update, not the other way around:

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
    // check for errors and parse the `data` here

    // when done
    dispatch_async(dispatch_get_main_queue()) {
        self.tableView.reload()  // this results in all of the `UITableViewDataSource` methods to be called
    }
}
task.resume()

Upvotes: 3

Related Questions