我有一个循环JSON数据并在tableview中显示的页面。 我正确地得到了正确但当它在页面上显示时,它非常慢。 我试图打印json以查看它检索json数据的速度有多快,而且非常快。 还有一件很奇怪的事情就是当它加载时,如果我拖动页面,一切都会立即显示。 下面是我在viewdidload函数中放入的代码
self.PoTable.separatorStyle = UITableViewCellSeparatorStyle(rawValue: 0)!
self.navigationController?.navigationBar.topItem?.backBarButtonItem = UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil)
PoTable.delegate = self
PoTable.dataSource = self
self.PoTable.addSubview(self.activityIndicatorView)
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
activityIndicatorView.startAnimating()
let url = NSURL(string: SharedClass().clsLink + "/json/POList.cfm")
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
if(error != nil) {
// If there is an error in the web request, print it to the console
println(error.localizedDescription)
}
var err: NSError?
let res = response as! NSHTTPURLResponse!
if(res != nil){
if (res.statusCode >= 200 && res.statusCode < 300){
self.jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as! NSDictionary
if(err != nil) {
// If there is an error parsing JSON, print it to the console
println("JSON Error \(err!.localizedDescription)")
}
var resultsArr: NSArray = self.jsonResult["results"] as! NSArray
// println(resultsArr)
self.PoList = PoInfo.poInfoWithJSON(resultsArr)
self.PoTable!.reloadData()
self.activityIndicatorView.stopAnimating()
self.activityIndicatorView.hidden = true
}
else{
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
SharedClass().serverAlert(self)
}
}else{
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
self.activityIndicatorView.stopAnimating()
SharedClass().serverAlert(self)
}
})
task.resume()
请帮助
答案 0 :(得分:1)
在if闭包中尝试此异步范围dispatch_async(dispatch_get_main_queue())
,如
dispatch_async(dispatch_get_main_queue()) {
if (res.statusCode >= 200 && res.statusCode < 300){
self.jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as! NSDictionary
if(err != nil) {
// If there is an error parsing JSON, print it to the console
println("JSON Error \(err!.localizedDescription)")
}
var resultsArr: NSArray = self.jsonResult["results"] as! NSArray
self.PoList = PoInfo.poInfoWithJSON(resultsArr)
self.PoTable!.reloadData()
self.activityIndicatorView.stopAnimating()
self.activityIndicatorView.hidden = true
}
}