Loading/Downloading an image from a URL in Swift

In this article, you will learn how you can download an image from a URL in the Swift language.

In the iOS application, image downloading from the image URL is the most common task. Apple provides us with a native library to download any data from any URL. There are many third-party libraries available on GitHub to download the images.

But in this tutorial, we are not going to use any third-party library. We will use the URLSession class provided by Apple itself.

What is the URLSession Class?

URLSession is a class in the Foundation framework that provides an API for downloading data from and uploading data to a server over a network connection. It uses a URL to identify the location of the resource and can be used to perform a variety of network requests, including GET, POST, PUT, and DELETE.


Here's an example of how you can use URLSession to make a GET request in Swift.

import UIKit let url = URL(string: "url_string")! let task = URLSession.shared.dataTask(with: url) { (data, response, error) in if let error = error { // handle error return } guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else { // handle error return } if let data = data { // process data } } task.resume()

This code creates a URL object representing the API endpoint and then creates a dataTask using the dataTask(with:) method of URLSession. The dataTask sends a GET request to the server and retrieves the data in the response. The completion handler is called when the request is complete, and it receives the data, response, and error as arguments.

You can use the response and data objects to handle the server's response and process the data as needed.

To load an image from a URL in Swift, you are going to use the same URLSession class to send a request to the server where the image is hosted. You will then use the data from the response to create an image with the UIImage class.

Here's an example of how you can do this


Step 1 − Create a class ImageDownloader and a method downloadImage().

Step 2 − Check for a valid URL object otherwise return.

Step 3 − Call the dataTask() method of the URLSession class.

Step 4 − Implement the completion callback in the dataTask() method.

Step 5 − Check for the error before moving on to the next step.

Step 6 − Convert the received data into UIImage object with if-let.


import UIKit class ImageDownloader { static func downloadImage(_ urlString: String, completion: ((_image: UIImage?, _ urlString: String?) -> ())?) { guard let url = URL(string: urlString) else { completion?(nil, urlString) return } URLSession.shared.dataTask(with: url) { (data, response,error) in if let error = error { print("error in downloading image: \(error)") completion?(nil, urlString) return } guard let httpResponse = response as? HTTPURLResponse,(200...299).contains(httpResponse.statusCode) else { completion?(nil, urlString) return } if let data = data, let image = UIImage(data: data) { completion?(image, urlString) return } completion?(nil, urlString) }.resume() } }


In the above example, you can see that validating the URL object before proceeding further is always a viable option. Once the request is completed, the completion

handler gives you data, response, and error. Verify whether an error was received or not before getting a valid image from the data.


import UIKit class TestViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.layer.cornerRadius = 16 imageView.layer.masksToBounds = true imageView.backgroundColor = UIColor(white: 0, alpha: 0.1)view.addSubview(imageView) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.widthAnchor.constraint(equalToConstant: 250).isActive = true imageView.heightAnchor.constraint(equalToConstant:250).isActive = true imageView.centerXAnchor.constraint(equalTo:view.centerXAnchor).isActive = true imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true ImageDownloader.downloadImage("https://picsum.photos/300") { image, urlString in if let imageObject = image { // performing UI operation on main thread DispatchQueue.main.async { imageView.image = imageObject } } } } }

Note that this code uses the dataTask method of URLSession to perform the request asynchronously. This means that the image will be loaded in the background, and the main thread will not be blocked. This is important to ensure that your app remains responsive while the image is being loaded.



Note that URLSession also provides other methods for performing network requests, such as uploadTask for uploading data to a server, and downloadTask for downloading data from a server. You can use these methods depending on your needs.