iOS — Loading remote image asynchronously with Image Cache support.

Bharathi Kumar
Dev Genius
Published in
2 min readJun 22, 2020

--

Photo by Yura Fresh on Unsplash

UIImageView is used to display images in iOS platform.
Loading a static image is a straight forward task. But what if we need to load the image from a remote server using a URL.

We will have to download the image using the given url, convert the data into UIImage object and then assign it to the UIImageView.

Let’s see how we can do that.

This block will download the url content and convert the data into UIImage object. Inside the success block you can free to use the image object to display it in the UIImageView.

Now everytime we need to set an image, we will have to use this block to download the image.

What if we cache the image and reuse it.

So, create a function in UIImageView extension, implement a function which takes image URL as parameter and store the downloaded image into NSCache object and sets the image to image view .

To show the image downloading status, we can add an activity indicator and animate it accordingly.

Advantages of using NSCache:

We don’t have to download same image multiple times.

NSCache is thread- safe and can be called from any thread.

iOS will handle clearing the cache data during memory warnings.

--

--