Nicholas Lim Nicholas Lim - 1 year ago 103
Swift Question

Slow loading of images in UITableViewController extracted from URL string

I'm trying to load images extracted from the web URL into the image view of each cell.

However, when i scroll the table the screen will freeze as I believe it is attempting to grab the images for each cell 1 by 1.

Is there a way i can make it asynchronous? The resources available out there currently is outdated or incompatible(running obj c) as I'm running on Swift 2

The relevant code I'm using within the table view controller is below :

override func tableView(newsFeedTableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let blogPost: BlogPost = blogPosts[indexPath.row]
cell.textLabel?.text = blogPost.postTitle
let unformattedDate = blogPost.postDate
//FORMATTING: Splitting of raw data into arrays based on delimiter '+" to print only useful information
let postDateArr = unformattedDate.characters.split{$0 == "+"}.map(String.init)
cell.detailTextLabel?.text = postDateArr[0]
let url = NSURL(string: blogPost.postImageUrl)
let data = NSData(contentsOfURL: url!)
cell.imageView!.image = UIImage(data: data!)//WHY SO SLOW!?


return cell

Answer Source

Try this

    var image: UIImage
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {() -> Void in
            // Background thread stuff.
            let url = NSURL(string: blogPost.postImageUrl)
            let data = NSData(contentsOfURL: url!)
            image = UIImage(data:data)

            dispatch_async(dispatch_get_main_queue(), {() -> Void in
                // Main thread stuff.
                cell.imageView.image  = image