从 NSURLConnection 加载 UITableView 时数据加载时间过长

Data taking too long to load when loading UITableView from a NSURLConnection

我的应用程序显示存储在我们服务器上的信息,这些信息会不断更新。因此,在浏览数据时,我将使用以下 class

检索到的数据加载到每个页面
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"
            }
        }
    )
  }
}

数据在 ViewController 之间快速加载很多时间,他们都使用此 class,但特别是在向后移动时,第一次通过从 sendAsynchronousRequest 掉落但没有成功。 ViewController 继续显示空白 table。然后上面的代码这次再次成功地在线程上运行并出现数据,但这最多可能需要 30 秒!下面的代码被 ViewDidLoad

中的 ViewController 使用
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()
}

谁能告诉我如何克服这个时间延迟问题

通过在主线程

上启用我的 Json 代码到 运行,上述两个响应都解决了我的问题