swift 2.3 中 View Controller 的数据加载速度非常慢
Data load very slow on View Controller in swift 2.3
我正在 View Controller 上显示 JSON Repsonse,但一些数据会立即使用密钥(开始日期)加载,但其他数据需要时间才能加载到 View Controller 我的代码:
var record : NSMutableDictionary!
var projectID = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
projectID = record["id"] as String
print("detail \(self.record)")
self.scrollView.contentSize = CGSizeMake(0,800)
singlePageData()
}
func singlePageData(){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
var errors: NSError?
let urlString = "http://phpyouth.com/clients/halfpricedgrannyflats/app/app_response.php?project_id=\(self.projectID)&project_page=Request"
print("URL RESPONSE \(urlString)")
let request = NSURLRequest(URL: NSURL(string: urlString), cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: 50)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { (data, response, error) in
if error != nil{
//handel error
var alertview = UIAlertView(title: "Network Error", message: "Data not received due to network connection.Try again...", delegate: self, cancelButtonTitle: "Ok")
alertview.show()
return
}
else{
if let responseData = data{
var jsonDict: NSDictionary = NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.MutableContainers, error: &errors) as NSDictionary!
println("Json dict value \(jsonDict)")
self.lblprojectName.text = jsonDict["name"] as? String
println("Project Name: \(self.lblprojectName.text)")
let starttime = jsonDict.objectForKey("start_time") as NSString
var interval:NSTimeInterval! = starttime.doubleValue
var date = NSDate(timeIntervalSince1970: interval!)
var format = NSDateFormatter()
format.dateFormat = "dd MMM, YYYY"
var timenewString: NSString = format.stringFromDate(date)
self.lblstartTime.text = timenewString
println("Start Time : \(self.lblstartTime.text)")
self.lblcurrentStage.text = jsonDict["current_stage"] as? String
println("Current Stage : \(self.lblcurrentStage.text)")
let completiontime = jsonDict.objectForKey("completion_time") as NSString
var intervalTime:NSTimeInterval! = completiontime.doubleValue
var datenew = NSDate(timeIntervalSince1970: intervalTime!)
var formatdate = NSDateFormatter()
formatdate.dateFormat = "dd MMM, YYYY"
var completiontimenewString: NSString = format.stringFromDate(datenew)
self.lblcompletionTime.text = completiontimenewString
println("Start Time : \(self.lblcompletionTime.text)")
self.lblManager.text = jsonDict["manager"] as? String
println("Manager : \(self.lblManager.text)")
}
}
}
task.resume()
})
}
我需要帮助解决这个问题。提前致谢
下载完成后在主线程上更新 UI:
dispatch_async(dispatch_get_main_queue()) {
// Update UI
}
在这种情况下:
func singlePageData(){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
var errors: NSError?
let urlString = "http://phpyouth.com/clients/halfpricedgrannyflats/app/app_response.php?project_id=\(self.projectID)&project_page=Request"
print("URL RESPONSE \(urlString)")
let request = NSURLRequest(URL: NSURL(string: urlString), cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: 50)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { (data, response, error) in
dispatch_async(dispatch_get_main_queue()) {
if error != nil{
//handel error
var alertview = UIAlertView(title: "Network Error", message: "Data not received due to network connection.Try again...", delegate: self, cancelButtonTitle: "Ok")
alertview.show()
return
}
else{
if let responseData = data{
var jsonDict: NSDictionary = NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.MutableContainers, error: &errors) as NSDictionary!
println("Json dict value \(jsonDict)")
self.lblprojectName.text = jsonDict["name"] as? String
println("Project Name: \(self.lblprojectName.text)")
let starttime = jsonDict.objectForKey("start_time") as NSString
var interval:NSTimeInterval! = starttime.doubleValue
var date = NSDate(timeIntervalSince1970: interval!)
var format = NSDateFormatter()
format.dateFormat = "dd MMM, YYYY"
var timenewString: NSString = format.stringFromDate(date)
self.lblstartTime.text = timenewString
println("Start Time : \(self.lblstartTime.text)")
self.lblcurrentStage.text = jsonDict["current_stage"] as? String
println("Current Stage : \(self.lblcurrentStage.text)")
let completiontime = jsonDict.objectForKey("completion_time") as NSString
var intervalTime:NSTimeInterval! = completiontime.doubleValue
var datenew = NSDate(timeIntervalSince1970: intervalTime!)
var formatdate = NSDateFormatter()
formatdate.dateFormat = "dd MMM, YYYY"
var completiontimenewString: NSString = format.stringFromDate(datenew)
self.lblcompletionTime.text = completiontimenewString
println("Start Time : \(self.lblcompletionTime.text)")
self.lblManager.text = jsonDict["manager"] as? String
println("Manager : \(self.lblManager.text)")
}
}
}
}
task.resume()
})
}
Note: In your case please update the syntax as your Swift version.
网络操作,即 Post 和 Get inside SinglePageData() 函数应该分开 class 并且应该提供回调方法,以便控制器在完整数据到达时得到通知.