sachin sachin - 1 year ago 107
Swift Question

Unable to update UILabel using dispatch_async method in swift iOS

I am setting json string value to UILabel using dispatch_async method. But Its unable to show updated value , but when I am printing label text, its showing updated value. here is my code-

override func viewDidLoad() {
get_detail_postmethod(url, params: params)

func get_detail_postmethod(url: String, params: String) {
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
request.HTTPMethod = "POST"
let postString = params
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error

if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")


let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
if let success = json["success"] as? Int
if((success) == 1){




}catch {
print("Error with Json: \(error)")

and below code for extract json data and set String value to UILabel-

func extract_json(jsonData:NSData)
let json: AnyObject?
do {
json = try NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
print("full data \(json!)")
} catch {
json = nil
let user_object = json!["opportunity_master"] as! NSArray
let data_block = user_object[0] as? NSDictionary
self.opp_title = (data_block!["opportunity_title"] as? String)!
self.event_sdate = (data_block!["event_start_date"] as? String)!

dispatch_async(dispatch_get_main_queue(), {
self.Event_title.text? = self.opp_title
self.Txt_event_date.text = self.event_sdate

print("event title label \(self.Event_title.text)")



I am not able to update values. Please suggest is there any other way to implement update UiLabel text.

Answer Source

This is solved by calling Viewcontroller like this-

let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let Opprt_Controller = storyboard.instantiateViewControllerWithIdentifier("Opprtunity_Event") as! Opportunity_Event

    self.navigationController!.pushViewController(Opprt_Controller, animated: true)