Software, Tech & Coding simplified.

Swift 5: How to Load an Image from a URL

To load an image from a URL in Swift, extend the UIImageView to support loading images with the following class extension:

extension UIImageView {
    func loadFrom(URLAddress: String) {
        guard let url = URL(string: URLAddress) else {
            return
        }
        
        DispatchQueue.main.async { [weak self] in
            if let imageData = try? Data(contentsOf: url) {
                if let loadedImage = UIImage(data: imageData) {
                        self?.image = loadedImage
                }
            }
        }
    }
}

Now you can call the loadFrom(URLAddress:) function for any UIImageView in your project.

Example. If you have an UIImageView called myImageView + an image behind a URL in example.com/image.png, you can get and show the image by:

myImageView.loadFrom(URLAddress: "example.com/image.png")

To test it with an actual image, replace the example.com/image.png with a URL that actually has an image behind it!

I hope this quick answer helps! To learn how the code actually works, read along.

How Does the Code Work

Basically, the code in the extension creates a URL object. Then it asynchronously fetches the image behind that URL. After the image data has arrived, the code converts it into a UIImage object.

Let’s take a closer look at the code:

First of all, we start by writing an extension for the UIImageView class:

extension UIImageView {
    ....
}

As the name suggests, an extension means adding behavior to an existing class. In this case, we want to extend the built-in UIImageView class to support loading images from a URL. By default, an UIImageView does not support this.

Then, we create a function called loadFrom(URLAddress:) for fetching an image from a URL:

func loadFrom(URLAddress: String) {
    ...
}

The first step in this function is to create a URL object based on the input URL address.

guard let url = URL(string: URLAddress) else {
    return
}

The guard let statement makes sure that creating a URL from the given URL address really works. If it does not, we exit the function right away without fetching any images.

Now that the URL object has been successfully created, we can fetch the image from that URL.

However, retrieving something over the internet takes a second. Thus, we perform the image retrieval as an asynchronous task. It grabs the image from the URL so that the program continues without waiting for the image retrieving to complete.

To perform an asynchronous task, we use DispatchQueue.main.async function.

DispatchQueue.main.async { [weak self] in
    ...
}

Inside this asynchronous block of code, we can retrieve the image data behind the URL.

To safely retrieve the image data, we use error handling (try? statement). This means we try to create a Data object from the url object. If this trial fails, we do not create an image:

if let imageData = try? Data(contentsOf: url) {
    ....
}

Then we try to convert this Data object into an UIImage object:

if let loadedImage = UIImage(data: imageData) {
   ...
}

If this succeeds, we have successfully retrieved an image from the URL and converted it into a UIImage object.

Finally, we want to actually display the downloaded image in the UIImageView:

self?.image = loadedImage

Conclusion

Today you learned how to load an image from a URL in Swift.

To recap, you can retrieve an image from a URL in Swift using an asynchronous task that:

  • Creates an URL object.
  • Retrieves the image data behind the URL.
  • Converts the image data into a UIImage object.
  • Displays the image in an UIImageView.

Commonly, you may want to extend your UIImageView class to support this behavior by writing an extension to the class.

Thanks for reading.

Happy coding!

Further Reading

50 Swift Interview Questions

Share

Share on twitter
Share on linkedin
Share on facebook
Share on pinterest
Share on email