Net Tanawat
Net Tanawat

Reputation: 43

Swift main thread doesn't work

I'm trying to update UILabel after get JSON data from server. I've tried many ways to fix it but it still doesn't work.

Here is my code

class ShopInformation: UIViewController {
var latitude = String();
var longitude = String();
var shopInformation:JSON = nil;

@IBOutlet weak var name: UILabel!

@IBOutlet weak var addres: UILabel!
override func viewDidLoad() {

    super.viewDidLoad()
    let url = NSURL(string: "http://localhost/whatapro/json/shopinformation.php?latitude=\(self.latitude)&longitude=\(self.longitude)")

    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {
        (data, response, error) in
        //                print(NSString(data: data!, encoding: NSUTF8StringEncoding))
        self.shopInformation = JSON(data: data!)
        print(self.shopInformation["response_data"][0])

        dispatch_async(dispatch_get_main_queue()) {

            self.name.text = self.shopInformation["response_date"][0]["name"].string
            self.addres.text = self.shopInformation["response_date"][0]["address"].string
        }

    }

    task.resume()
}
}

I also tried this way

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
        dispatch_async(dispatch_get_main_queue()) {
            self.name.text = self.shopInformation["response_date"][0]["name"].string
            self.addres.text = self.shopInformation["response_date"][0]["address"].string
        }
    }

Thank you

Upvotes: 1

Views: 124

Answers (1)

Duncan C
Duncan C

Reputation: 131398

Expand your code to break out the values from your JSON into a separate variable. Set a breakpoint after you assign the variable, then examine the value in the debugger, and also examine the values of your self.name and self.addresoutlets.

My guess is that one or both of your outlets is not connected.

(The first version of your code, using dispatch_async(dispatch_get_main_queue()), looks correct.)

Upvotes: 1

Related Questions