Javatpoint Logo
Javatpoint Logo

Image Caching with AlamofireImage

In the previous section of this tutorial, we have built an application in which, we needed to download an image from the URL (sent by an API) and set it on the image view. However, we have downloaded all the images in real-time using the following code in the tableview DataSource method.

If we observe into that application, scrolling through the tableview has been a very tedious task since the image is being downloaded at the main thread. However, the issue will persist if we keep on downloading and setting up the image from an image URL on runtime.

To resolve this issue, we can use AlamofireImage, which simplifies the image downloading task. Here, we can use it to download an image, and simultaneously we can use NSCache to add the image into the cache once downloaded.

Setup

AlamofireImage works on the top of Alamofire, which means we need to install both these libraries to work with AlamofireImage. We can install AlamofireImage by using Podfile, in which we will add the following line.

Once the pod installation for AlamofireImage completes, we can import it using the import statement in swift.

To use AlamofireImage to download the images, first, we need to set up the cache by using the following code.

Now, we need to request to download the image. For this purpose, we use the request method of Alamofire.

Since we have added the image in the Image Cache, we need to retrieve it back from the cache while populating it to the image view.

Example

Here, we will continue with the ArtistProject we created in the previous section of this tutorial. However, this time we will store all the images that we are going to load in the tableview, in the image cache, and use that image cache while loading the image.

However, we will make some changes to the ViewController.swift file. All other files of the project will remain the same.

ViewController.swift

Now, if we run the project, we will not face any problem while scrolling since we are not downloading the images this time at runtime; however, we are retrieving the images from the cache.








Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA