I'm working on an app in Swift 2.2.
I created a tabbed application from the initial template. I then added some code to my FirstViewController class, in order to download, parse, and display some JSON-formatted data.
This is the contents of my FirstViewController.swift file:
import UIKit
class FirstViewController: UIViewController {
@IBOutlet weak var siteNameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var siteName = ""
let requestURL: NSURL = NSURL(string: "http://wheretogo.com.mx/backends/service.php")!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in
let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
//print("Everyone is fine, file downloaded successfully.")
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
if let appInfo = json["appInfo"] as? [[String: AnyObject]] {
siteName = appInfo[0]["siteName"] as! String
self.siteNameLabel.text = siteName
}
}catch {
print("Error with Json: \(error)")
}
}
}
task.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Fetching and parsing the data actually works. The problem is that the data is only displayed when I select the second tab and then go back to the first.
When it loads the label, it has the default text and it changes when I go to another tab and come back to the first, then the self.siteNameLabel.text = siteName.
I think an init can solve it, but I don't know how, or maybe a delay?
Or how can I handle the downloading data before my first view controller load.
Thanks in advance.