0

I'm trying to fill a UITableView with data that I acquire via a DataTaskWithURL call. However, the tableview has loaded before the completion handler has started.

I searched for this problem and found things about moving it to the main thread but that didn't seemed to work. Any idea on how I can move it to the right que before the tableview had loaded?

My code:

    var jsonData: JSON = []

func getRequestForTableView() {

    let urlPath = "[URL]"
    let url: NSURL = NSURL(string: urlPath)!
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in

        let json = JSON(data: data)

        println(json.count)
        self.jsonData = json
    })
    task.resume()
}
Alex
  • 781
  • 10
  • 23
Ricardo42
  • 103
  • 1
  • 1
  • 7
  • 1
    Reload the table view at the end of the completion handler (but do the reload on the main thread). – rmaddy Feb 11 '15 at 16:07
  • 1
    ... and show a progress view while obtaining data, or give some other feedback to let the user know something is going on – Antonio Feb 11 '15 at 16:07
  • 1
    Assume that `self.jsonData` is your data source. Calls `dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() }` on the last line of this `completionHandler`. – yusuke024 Feb 11 '15 at 18:54
  • Thanks, I tried it and it worked! – Ricardo42 Feb 11 '15 at 19:28

1 Answers1

1

Needs to Check response code and Your Data first. Response code like 200. If there are thing you are looking for, You need to Reload TableView in your block after confirmation of your response.

Make sure you correctly interpret your data in TableView.

Reload TableView // Swift

dispatch_async(dispatch_get_main_queue(), { () -> Void in
    self.tableView.reloadData()
})

Response Code // iOS

if ([response statusCode] == 200) {
           //reload table here             
}
Chetan Prajapati
  • 2,249
  • 19
  • 24
  • Hi Chetan, I don't completely understand what you're suggesting. Could you perhaps provide a code example? – MattG Apr 20 '15 at 13:51