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

My app displays information stored on our server, which is updated constantly. therefore when browsing the data I load each page with data retrieved using the following 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
        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"

The data loads quickly a lot of the time moving between ViewControllers who all use this class but particularly when moving backwards the first pass through drops through from the sendAsynchronousRequest without success. The ViewController carry on and displays a blank table. Then the above code runs on the thread again successfully this time and the data appears but this can take up to 30 seconds! The code below is used by the ViewController in 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
             if let code = jsonItem.valueForKey("code") as? String

Could someone please tell me how I can overcome this time delay issue

Source: json

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.