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:
About B:
NSURLRequestUseProtocolCachePolicy
. URLRequest
now that the image is asked for download has been already downloaded and cached? About C:
About D:
In summary: which of the options would be the most efficient and appropriate for my scenario, and why?
From what I inferred about your question "what I want is to avoid to download an image that was already downloaded. And I would like them to have some expiration time."
To avoid images from downloading again, you can implement the following use case where, you store the images in the NSCache using the urls of the image itself.
This would be something like as discussed in the link .
For the expiration time case, if you want to remove all images at a particular expiration time, then just make a check for that scenario and empty the cache.
For the case where you want to remove the individual images , based on their expiration time, you can check the response from the server for the expiration key, and again remove cache in case the limit has been breached.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.