Json request for slow scrolling tableview

1

I have an application that returns a json to a tableview, however, every time I roll the cells it kind of chokes, I've already been told I'd have to leave the asynchronous json return function ... Does anyone know how to treat this in Swift?

There are only 10 lines with image and next to a label, but with tests done, since the problem of slowness is only with the loading of the images that have in the cells in the method cellForRowAtIndexPath if I comment from the line that grabs the url of the images until the end is good, it is as if the CellForAtIndexPath method made every request of the images with each scroll.

The part of the code that you have pro ...

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell:Cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! Cell


        cell.info.text = arrayJson[indexPath.row]
        cell.info.font = UIFont.systemFontOfSize(12.0)

        if let url = NSURL(string: self.arrayJsonImages[indexPath.row]) {

             let data = NSData(contentsOfURL: url)

                cell.imagem.contentMode = UIViewContentMode.ScaleAspectFit
                cell.imagem.image = UIImage(data: data!)
                cell.imagem.layer.masksToBounds = true;
                cell.imagem.layer.cornerRadius = 15;

        }


            return cell


    }
    
asked by anonymous 04.11.2015 / 20:54

1 answer

2

In fact you will need to download asynchronously from this image so you do not get these hangs on your table.

Start with something like this:

if let imageUrl = NSURL(string: arrayJsonImages[indexPath.row]) {
    let request = NSURLRequest(URL: imageUrl)
    let requestQueue : NSOperationQueue = NSOperationQueue()

    NSURLConnection.sendAsynchronousRequest(request, queue: requestQueue, completionHandler: { (response, responseData, error) -> Void in
        if error == nil {
            cell.image = UIImage(data: responseData!)
        }
    })
}

This already solves your crash problem. Now to further optimize, it would be interesting to store these images in a cache directory, so you will not need to download every time if this is the case.

If you want something more robust, a placeholder, the management of cache and etc, you can search for something already ready like for example a SDWebImage , which is a category of UIImageView .

    
09.11.2015 / 11:37