iOS UITableView lazy loading of images

Mohit Kumar
Mac O’Clock
Published in
3 min readApr 21, 2020
Photo by Safar Safarov on Unsplash

In this article, I am going to cover how can we implement lazy loading in UITableView. In our day to day development, this is a very common scenario where we need to display images from URL in our UITableView. For this, we have several libraries available (e.g SDWebImage) in GitHub.

In this article, I will also explain how to write your own class which work as SDWebImage. We can write minimal code to achieve the same functionality without increasing app size too much because in a third-party library contains lots of extra code which is not even of use for us.

So let’s start step by step, as a first step we can create UIImageView extension in the following way:

The code above performs the following tasks:

  1. It accepts image URL and placeholder image, initially it set placeholder image if available to avoid blank screen. In case if placeholder image was not passed, we just set background colour just to avoid blank white space.
  2. In the second step, we just downloaded image and set to current UIImageView instance.

Problem with the above code:

This code will work when we are not using any reusable views, but our UITableViewCell is reusable, so if we call setImage() for each cell, it will not handle reusable properly. So you can see lot’s of image fluctuation in your UI, because each time we call setImage, it just makes a downloading API call to the image. So before it was downloaded and displayed, the UITableViewCell is reused for another index, in that case once downloading for the old image will be completed, it will set it to UITableViewCell reference which is now reused for the new index. So it will result in the wrong image on current indexPath.

To avoid this problem we can:

  1. Keep a property at the class level which stores the current URL to be called.
  2. Once URL is downloaded, it will match it with the latest URK, if the latest URL and downloaded URL is same than we just display image else skip display part.

With the above approach, we have a problem that extension in Swift doesn’t allow stored properties. A workaround for that we can either use Objective-C associated objects OR can use the following approach:

If you look for changes, we did the following modifications in the code:

  1. Added static variable (stored property not allowed) to store a URL that corresponds to a class reference.
  2. When displaying the image, just checking if the latest URL is the same as the URL for which the image is downloaded.

With the above codebase, we can achieve complete functionality for lazy loading in UITableView. I haven’t implement caching in SDWebImage, this can be added as an enhancement.

You can find a complete working example here:

--

--