title: How to cache images using URLSession in Swift
body: <p>I would like to enhance the code below to cache images and only download them if they haven't been cached previously. I can't seem to find any good examples of how to use URLSession object to do this.  </p>
  
  <pre><code>extension UIImageView {
      func loadImageWithURL(_ url: URL) -&gt; URLSessionDownloadTask {
          let session = URLSession.shared
  
          let downloadTask = session.downloadTask(with: url, completionHandler: { [weak self] url, response, error in
  
              if error == nil, let url = url,
                  let data = try? Data(contentsOf: url), let image = UIImage(data: data) {
  
                      DispatchQueue.main.async {
                          if let strongSelf = self {
                              strongSelf.image = image
                          }
                      }
              }
          })
          downloadTask.resume()
          return downloadTask
      }
  }
  </code></pre>