SilverHood
SilverHood

Reputation: 723

Tab with UITableView takes long to load

I have a tab that contains a UITableView. The UITableView loads JSON from a server. Here are some lines in my viewDidLoad():

// Register the UITableViewCell class with the tableView
        self.tableView?.registerClass(UITableViewCell.self, forCellReuseIdentifier: self.cellIdentifier)
        var tblView =  UIView(frame: CGRectZero)
        tableView.tableFooterView = tblView
        tableView.backgroundColor = UIColor.clearColor()

        startConnection()

Here is my startConnection():

func startConnection() {
        let url = NSURL(string: "some correct URL")
        var request = NSURLRequest(URL: url!)
        var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)
        if data != nil {
            var json = JSON(data: data!)

            if let jsonArray = json.arrayValue {
                for jsonDict in jsonArray {
                    var pageName: String? = jsonDict["title"].stringValue

                    //some code

                }
            }
            activityIndicator.stopAnimating()
        } else {
            println("No data")
            activityIndicator.stopAnimating()
            var alert = UIAlertController(title: "No data", message: "No data received", preferredStyle: UIAlertControllerStyle.Alert)

            let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in

            }
            alert.addAction(cancelAction)

            let OKAction = UIAlertAction(title: "Retry", style: .Default) { (action) in
                self.startConnection()
            }
            alert.addAction(OKAction)
            self.presentViewController(alert, animated: true, completion: nil)
        }
    }

After the first load, the tab will show upon clicking. I am thinking if it is the NSURLConnection.sendSynchronousRequest causing the lag. Any advice and suggestion? I don't really know how to use sendAsynchronousRequest either =/ Please help. Thank you! =D

Upvotes: 0

Views: 70

Answers (2)

Ian
Ian

Reputation: 12768

Although there are several ways to get data from a website, the important thing is that you execute your UI updates on the main thread using dispatch_async(dispatch_get_main_queue()) {}. This is because URL tasks such as NSURLSession.dataTaskWithURL or NSURLConnection.sendAsynchronousRequest() {} execute on a background thread so if you don't explicitly update UI on the main thread you will often experience a lag. Here's what a simple request looks like:

func fetchJSON(sender: AnyObject?) {

    let session = NSURLSession.sharedSession()
    let url: NSURL! = NSURL(string: "www.someurl.com")

    session.dataTaskWithURL(url) { (data, response, error)  in

        var rawJSON: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: .allZeros, error: nil)

        if let result = rawJSON as? [[String: AnyObject]] {
            dispatch_async(dispatch_get_main_queue()) {
                // Update your UI here ie. tableView.reloadData()
            }
        }
    }.resume()
}

Upvotes: 1

Adeel Ur Rehman
Adeel Ur Rehman

Reputation: 566

You can do it like this:

let url:NSURL = NSURL(string:"some url")
let request:NSURLRequest = NSURLRequest(URL:url)
let queue:NSOperationQueue = NSOperationQueue()

NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
    /* Your code */
})

Upvotes: 1

Related Questions