I have a UITableViewController that contains a static UITableView from which you can request quotes and buy or sell a stock. I handle all communications to the backend in a separate ServerCommunicator class. When a request completes, the ServerCommunicator calls the delegate (the tableViewController) which updates the fields in the tableView.
In the main queue, I call tableView.reloadData and display the fields.
The problem is that the fields display immediately but show stale values. When I select a row by clicking on it, however, value is updated.
What am I doing wrong?
class AddStockTableViewController: UITableViewController, ServerCommunicatorDelegate {
………..
override func viewDidLoad() {
super.viewDidLoad()
nameLabel.hidden = true
symbolLabel.hidden = true
quoteLabel.hidden = true
changeLabel.hidden = true
….….
}
@IBAction func getQuoteAction(sender: UIButton) {
if let symbol = getQuoteTextField.text {
serverCommunicator.updateQuote(symbol, delegate: self)
}
}
func didCompleteRequest(data : NSData)
{
quote = parseQuote(data)
self.symbolLabel.text = "(\(self.quote.symbol))"
self.nameLabel.text = self.quote.name
self.quoteLabel.text = "\(self.quote.currentPrice)"
self.changeLabel.text = “\(self.quote.change)"
…….
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
self.nameLabel.hidden = false
self.symbolLabel.hidden = false
self.quoteLabel.hidden = false
………
}
}
class ServerCommunicator
{
func sendRequest(requestURL : String, requestString : String, delegate : ServerCommunicatorDelegate)
{
if let requestData = requestString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false){
let request = NSMutableURLRequest(URL: NSURL(string: requestURL)!)
request.HTTPMethod = "POST"
let urlSession = NSURLSession.sharedSession()
let task = urlSession.uploadTaskWithRequest(request, fromData: requestData, completionHandler: {(data, response, error) -> Void in
if error != nil {
println(error.localizedDescription)
}
else {
delegate.didCompleteRequest(data)
}
})
task.resume()
} else {
print("Could not encode requestString to data")
}
}
…….
}