Get UIImage from URL March 21, 2017

Loading in images asycronously from the web is something you'll probably do commonly in a project. After coming across the problem and then solving it, I found there weren't solid solutions on StackOverflow or other blogs addressing this simple, common problem with a good solution.

Drop these functions into the global scope. I add them to a Common.swift or Helpers.swift file.

            
      func getDataFromUrl(url: URL, completion: @escaping (_ data: Data?, _  response: URLResponse?, _ error: Error?) -> Void) {
          URLSession.shared.dataTask(with: url) {
              (data, response, error) in
              completion(data, response, error)
              }.resume()
      }

      func downloadImage(url: URL, completion: @escaping (UIImage?) -> Void) {
          print("Download Started")
          getDataFromUrl(url: url) { (data, response, error)  in
              guard let data = data, error == nil else { return }
              print(response?.suggestedFilename ?? url.lastPathComponent)
              print("Download Finished")
              DispatchQueue.main.async() { () -> Void in
                  completion(UIImage(data: data))
              }
          }
      }
      
          

The downloadImage() function takes in a url and returns a UIImage. Throughout the project whenever you need to load in an image from a URL just call this function:

            
      let urlString = "http://example.com/image.jpg"

      if let imageURL = URL(string: urlString) {

        downloadImage(url: imageURL, completion: { (image) in
          self.imageView.image = image // here you set the image on the imageView
      })
      
          

That's it! Have fun and #CompileSwift.