SwiftBits: Caching Images

Malcolm Kumwenda
Swift2Go
Published in
3 min readAug 10, 2018

--

I will be starting a series of short posts where I share a small snippet of code. These will be short reads and focus on one main idea.

In the first post of this series, we will look at loading images in our application more efficiently by making use of a cache.

URLCache

The URLCache class implements the caching of responses to URL load requests by mapping NSURLRequest objects to CachedURLResponse objects. It provides a composite in-memory and on-disk cache, and lets you manipulate the sizes of both the in-memory and on-disk portions.

UrlCache gives us the ability to cache responses made to URL requests. We can use this cache to store all response data. It is not limited to images. For this post, we will only use it for images.

Create a file named UIImageView+Cache.swift. Then create an extension to UIImageView and add the code below.

load image from url function.

Code Breakdown

  1. Firstly we create a URL from the string that is passed into our function. If the URL fails to instantiate we return and do not perform any further operations.
  2. We create our cache from the shared URLCache. This is the default cache which is suitable for most uses cases. Then next we create a URLRequest from the URL.
  3. We make use of a userInitiated queue to do the work. This is done so that we do not block the main thread and block our apps UI as we load the image. First we check if the image we are trying to request is in our cache already.
  4. If it is in the cache we display the image. We will discuss the implementation of the transition function in the next section.
  5. When the image can not be found in the cache we then go ahead and make a request for the image using URLSession. We check that we have data and a response. We also validate that the response is a success response before we perform any work. Finally we create the cachedData from the response and the data and store it into the cache. Then call transition.

UIImageView Extension

Inside the extension we created above to UIImageView add the function below. Note that when the function is called above it is always on the main thread.

UIImageView+Transition

Here we make a helper function that applies a cross dissolve transition to our UIImageView. This will make the image appear with a smooth animation rather than just appearing. Small things like this can improve user experience and make your app stand apart.

Hope you enjoyed this read and found it informative. 😊

Further Reading:

Source Code:

--

--