sachin sachin - 3 months ago 17
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() {
super.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
print("param=\(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
print("error=\(error)")
return
}

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)")
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
print(json)
if let success = json["success"] as? Int
{
if((success) == 1){

self.extract_json(data!)

}
else{

}
}

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


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
return
}
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(), {
print(self.opp_title)
self.Event_title.text? = self.opp_title
self.Txt_event_date.text = self.event_sdate
self.Event_title.setNeedsDisplay()

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

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)