Below is my ViewController code. The println in GetRequest prints the correct data that it receives from the HTTP GET request. At this point, tableData has 10 key-value pair
Rearrange the orders of the method calls:
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
var apiInfo = GetWaitTimes()
GetRequest(apiInfo.BorderCrossingApi+"?AccessCode="+apiInfo.AccessCode)
tableView.reloadData()
}
Explanation: you set the delegate and dataSource before you GetRequest() so the dataSource won't be nil.
The problem is that GetRequest
runs asynchronously. So you have to reloadData
inside the completionHandler
of dataTaskWithURL
:
let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
// do all of your existing stuff here
dispatch_async(dispatch_get_main_queue()) {
self.tableData = LatestWaitTimes
self.tableView.reloadData()
}
})
task.resume()
You can remove the reloadData
from within viewDidLoad
.
Try this it may help you
you can add a callback (for reload tablview) in GetRequest
function and run the callback after parser json in completionHandler
Maybe When you set the delegate with tableview, tableData still be nil (waitting for http response)
this is my code .you can refer to
demand.loadDataFromServer(self.view, done: { () -> Void in
self.demands = demand.getDemandDataList()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
})
func loadDataFromServer(view:UIView,done:(() -> Void)!){
var request:HttpRequest = HttpRequest(view:view)
request.GET(getDemandListURL, parameters: nil, success: { (dict) -> Void in
self.demandLists = dict["data"] as NSMutableArray
done()
}, failed: { (dict) -> Void in
}) { (error) -> Void in
}
}