URLSessionDownloadTask Disk Caching

I'm looking for some guidance on best practices for caching downloaded images and only downloading them again when they have changed on their remote host. It seems like a common enough scenario that there would be some standard practices, but I have been dissatisfied with the discussions and libraries I have found so far.

The basic need is to
  • download images of unknown size, type, and location on-demand

  • cache them to improve load time and prevent unnecessary network traffic

  • know when to re-download the image when the source image has changed

Since I do not have control of the images, I prefer to use URLSessionDownloadTask to write the files directly to disk, then use CGImageSourceCreateThumbnailAtIndex to create appropriately-sized thumbnails rather than download the (potentially large) full-size image into memory. This works great, but to my knowledge, lacks the caching support that URLSessionDataTask offers.

What, then, is the proper way for me to update my disk cache of images to ensure that they are up-to-date with their network sources? I have considered making a HEAD request to check the LastModified or ETag headers, but this requires the host to provide this information, which I cannot always rely on. Is this essentially how URLSession and URLCache manages caching under-the-hood?

As I was writing this post, I came across the URLSessionDataDelegate method urlSession(_:dataTask:didBecome:) and URLSession.ResponseDisposition. This seems like an intriguing option as well, whereby I begin every task as a URLSessionDataTask, then based on the results of the headers, cancel the task or convert to a download task.

Am I just at the liberty of the image hosting service to provide a LastModified date or is there a more sophisticated approach that I'm not considering?
URLSessionDownloadTask Disk Caching
 
 
Q