Tutorial details

Developing iOS Apps Using Swift Tutorial | App Code for Sale | Preview

Developing iOS Apps Using Swift Tutorial - Part 5 – Async image loading and caching | iOS Tutorial

How to create an amazing new blazingly fast table view!

Overview PAGE TOP

In parts 1 through 4 we went over some basics of Swift, and set up a simple example project that creates a Table View and a puts some API results from iTunes inside of them. If you haven’t read that yet, check out Part 1.

This table is slow! Let’s speed it up. PAGE TOP

So, we now have the functionality we’re looking for, but if you run this yourself you’ll see its super slow! The issue is that the images in these cells are downloading on the UI thread, one at a time, and they aren’t being cached at all. So let’s fix that.

Let’s start by adding a dictionary as a member for our class:

var imageCache = NSMutableDictionary()

Now, in our cellForRowAtIndexPath method, we want to do quite a few things. Here’s the final version of the method we’re going to have. This link opens up in a new tab and will make following along a little easier.

First off, there have been some issues for people trying to mess with the search API terms when they get back data they don’t expect. So let’s add a check for the trackName value in our dictionary we get back:

// Add a check to make sure this exists<br />let cellText: String? = rowData["trackName"] as? String<br />cell.text = cellText

Before we download the real image let’s make sure to set the cell’s placeholder image. This is required if you want the cell to actually include an image view. Otherwise even loading in our image later will not show up! Create a blank image (I’m using 52×52 pixels, but it doesnt matter much) and Import it in to your project by click+dragging a file from finder in to you Xcode project, name it Blank52, and then set our cell to use this image. You can just grab my image file here.

cell.image = UIImage(named: "Blank52")

Now our app should be less prone to crashing, and will now always have an image cell.

Put Image Downloading On A Background Thread PAGE TOP

Next, we want to fire off a background thread to handle the image download. Swift doesn’t seem to have it’s own version of GCD, so we’re going to use the existing Obj-C API to do this using dispatch_async.

We open up this block using the GCD API

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {

This allows our code to move on outside of this block and return the cell, but also keep the download and image stuff in the background. This is important for a responsive UI experience.

Moving in to the block, we now should first check our image cache to see if this image has been downloaded before. We use the following to set an optional variable called image.

var image: UIImage? = self.imageCache.valueForKey(urlString) as? UIImage

If the image doesn’t exist (and initially it won’t) we need to download it. There are a couple of ways to initiate a download. Previously we used NSData’s dataWithContentsOfFile, but here we’re going to switch to NSURLConnection’s sendAsynchronousRequest, more similar to how our API works. The reason being is that we want to send off lots of small requests for images real quick. So let’s do that.

This part probably won’t be formatted to well in my blog, so open up the gist and look at line 35. What we’re doing here is calling NSURLConnection’s static method sendAsynchronousRequest, which takes a function as a parameter for completionHandler. Lines 36 through 46 are the contents of the block.

Inside the block we will get back a few variables: response, data, and error.

On line 36 we check if an error exists, and if not, proceed to create a UIImage from the data on line 38. Line 37 was our previous method for reference.

image = UIImage(data: data)

Now on line 41 we set the image cache to save our fancy new image with a key of the image URL. Using the URL as the key means we can find the image in our dictionary any time it pops up, even in a completely different context.

self.imageCache.setValue(image, forKey: urlString)

Finally, we set the cell image:

cell.image = image

Okay! Give the project a run and see our amazing new blazingly fast table view!

The complete code up to this point is available on Github as a branch ‘Part5‘.

You can also download the Part 5 code as a zip here.

Reference PAGE TOP


0 Comments Leave a comment

Please login in order to leave a comment.

Newest first

to your Chupamobile Account.

The Easiest way to Launch your next App or Game.

Join Chupamobile and get instant access to thousands of ready made App and Game Templates.

Creating an account means you’re okay with Chupamobile’s Terms of Service and Privacy Policy.