3

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.

Jason
  • 635
  • 1
  • 9
  • 21

1 Answers1

1

This may have something to do with the thread you use to update your UI. Note that the completion block utilised by dataTaskWithRequest is performed on a background thread.

Since Apple only allows UI updates to be done on the main thread, you can solve this issue by using a dispatch block like so (as mentioned here):

dispatch_async(dispatch_get_main_queue(), {
    self.siteNameLabel.text = siteName
})

Also, note that if you want the data that your UI depends on to update each time FirstViewController is shown, you should have your code in viewDidAppear rather than viewDidLoad.

Hope this helps!

Community
  • 1
  • 1
Jason
  • 635
  • 1
  • 9
  • 21