I'm need to implement the common scenario of having a table view with N cells where each of those cells needs to download an image to be displayed within it.
The service protocol to call to download the images could be either HTTP or HTTPS.
I am using an URLSessionDownloadTask
this way:
func downloadImage(urlStr: String, completion: @escaping (UIImage?, Error?) -> Void) {
let url = URL(string: urlStr)
let request = URLRequest(url: url!)
let task = session.downloadTask(with: request, completionHandler: {
(fileUrl, response, error) in
// Call 'completion' depending on result
})
task.resume()
}
Where session
is an URLSession
with default configuration and associated operation queue:
self.session = URLSession(configuration: configuration, delegate: nil, delegateQueue: self.operationQueue)
So, what I want is to avoid to download an image that was already downloaded. And I would like them to have some expiration time.
I've read some articles and posts and I'm not completely clear about the differences between the options I found:
A. Using FileManager
to actually store the image as a file, and removing it after checking the expiration time.
B. Setting the cachePolicy
property of URLRequest
.
C. Using URLCache
D. Using NSCache
About A:
- What is actually the difference between storing the image as file and using a cache? Could have the file storage offer any benefit that a cache does not? Those images are not user-related, I can download them from a server when needed.
About B:
- I read Apple's documentation about that, but I don't fully understand if for my scenario I should use
NSURLRequestUseProtocolCachePolicy
. - How does this option actually work? It is enough to set the policy and then you don't have to care about anything else? How does the
URLRequest
now that the image is asked for download has been already downloaded and cached?
About C:
- How does it should be correctly implemented? Could anybody provide me an example/tutorial in case this is the best approach? What about expiration date?
About D:
- I found an example I understood, but would it be a good approach having the previous options? What about expiration date also here?
In summary: which of the options would be the most efficient and appropriate for my scenario, and why?