1
我的应用程序显示存储在我们服务器上的信息,该信息会不断更新。因此,在浏览数据时,我加载数据的每个页面使用下面的类从NSURLConnection加载UITableView时加载的数据时间过长
public class GetRemoteData {
class func getDataFromServer(success: ((svrData: NSData!) -> Void)) {
//Set http connection settings
let httpMethod = "GET"
let timeout = 10
let url = NSURL(string: ViewController.gVariables.gUrl)
let urlRequest = NSMutableURLRequest(URL: url!,
cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData,
timeoutInterval: 10.0)
let queue = NSOperationQueue()
//Initiate connection to server
NSURLConnection.sendAsynchronousRequest(
urlRequest,
queue: queue,
completionHandler: {(response: NSURLResponse!,
data: NSData!,
error: NSError!) in
//If data recieved load into svrData
if data.length > 0 && error == nil{
let json = NSString(data: data, encoding: NSASCIIStringEncoding)
if let urlData = json {
let data = json!.dataUsingEncoding(NSUTF8StringEncoding)
success(svrData: data)
}
}else if data.length == 0 && error == nil{
ViewController.gVariables.gError = "No data was recieved, please check your connection"
} else if error != nil{
ViewController.gVariables.gError = "Error occurred - \(error), please check your connection"
}
}
)
}
}
数据快速加载大量的时间ViewControllers谁向后移动通过滴第一遍时都使用这个类,但特别之间移动检索通过从sendAsynchronousRequest没有成功。 ViewController继承并显示一个空白表。然后上面的代码再次在线程上成功运行,数据出现,但这可能需要30秒!下面的代码是在viewDidLoad中使用的视图控制器
GetRemoteData.getDataFromServer { (svrData) -> Void in
let jsonDict = NSJSONSerialization.JSONObjectWithData(svrData, options: nil, error: nil) as! NSDictionary
if (ViewController.gVariables.gError != "") {
let alertController = UIAlertController(title: "Warning", message:
ViewController.gVariables.gError, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil))
alertController.presentViewController(alertController, animated: true, completion: nil)
}
if let items = jsonDict["products"] as? NSArray {
for jsonItem in items {
if let name = jsonItem.valueForKey("name") as? String
{
self.brandNames.addObject(name)
}
if let code = jsonItem.valueForKey("code") as? String
{
self.brandCodes.addObject(code)
}
}
}
self.tableView.reloadData()
}
可能有人请告诉我,我该怎么克服这个时间延迟问题
我解释了它[这里](http://stackoverflow.com/questions/30625275/swift-tableview-displays-json-data-very-slow/30625717#30625717)你应该把你的json查询'dispatch_async(dispatch_get_main_queue())' –
以这种方式重载tableview:'dispatch_async(dispatch_get_main_queue()){ self.tableView.reloadData() }' –
这对我有效,谢谢 – user616076