# How do I load an image by URL on iOS device using Swift?

To load an image in iOS using swift we’ll make use of simple data Task session. The image needs to be loaded in background because it may be of any size and we don’t want it to stop our main view’s operations.

Let’s see this with help of an example. Create an empty project and add an empty Image view.

Create its outlet and then we’ll write the code to get image from an URL. This is how our application looks at the moment.

Now, let’s add code to get image from an URL.

func getData(from url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {
}
getData(from: url) {
data, response, error in
guard let data = data, error == nil else {
return
}
DispatchQueue.main.async() {
self.image = UIImage(data: data)
}
}
}

When we run this code, it will download image from the URL, we can create an image object and initialize our imgView with the new object.

But let’s create an extension of this method and use.

extension UIImageView {
func getData(from url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {
}
getData(from: url) {
data, response, error in
guard let data = data, error == nil else {
return
}
DispatchQueue.main.async() {
self.image = UIImage(data: data)
}
}
}
}

Now, In our viewDidLoad (or any other place you like) add the following code.

override func viewDidLoad() {
}