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?) -> ()) {
   URLSession.shared.dataTask(with: url, completionHandler: completion).resume()
}
func downloadImage(from url: URL) {
   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?) -> ()) {
      URLSession.shared.dataTask(with: url, completionHandler: completion).resume()
   }
   func downloadImage(from url: URL) {
      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() {
   super.viewDidLoad()
   let url = URL(string: "https://static.independent.co.uk/s3fs-public/thumbnails/image/2017/09/12/11/naturo-monkey-selfie.jpg?w968h681")
   self.imgView.downloadImage(from: url!)
}

When we run this code on our device, we get the following result.

raja
Published on 18-Apr-2019 06:32:58
Advertisements