我正在使用 dispatch_async 方法将 json 字符串值设置为 UILabel。但是它无法显示更新值,但是当我打印标签文本时,它显示更新值。这是我的代码-
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()
}
下面的代码用于提取 json 数据并将字符串值设置为 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)")
})
}
我无法更新值。请建议是否有任何其他方法来实现更新 UiLabel 文本。
最佳答案
这可以通过像这样调用 Viewcontroller 来解决-
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let Opprt_Controller = storyboard.instantiateViewControllerWithIdentifier("Opprtunity_Event") as! Opportunity_Event
self.navigationController!.pushViewController(Opprt_Controller, animated: true)
关于ios - 无法在 iOS 中使用 dispatch_async 方法更新 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39077553/