I am using the SDWebImage
library to cache web images in my app:
https://github.com/rs/SDWebImage/blob/master/README.md
Current Usage:
SDWebImage flow:
1) SDWebImage
caches image retrieved from the server
2) SDWebImage
uses url is a key to the get image from cache
3) SDWebImage
checks:
if it is able to get the image from cache - OK
if no (e.g url was changed) - not able to get the image from cache
so actually, you will get empty ImageView(s) and SDWebImage
must retrieve images from the server again
You can use options
parameter.
Swift version:
imageView.sd_setImage(with: URL(string: URLWithString:profilePictureUrl),
placeholderImage: UIImage(named: "placeholder"),
options: .refreshCached,
completed: nil)
Objective-C version:
[imageView sd_setImageWithURL:[NSURL URLWithString:profilePictureUrl]
placeholderImage:[UIImage imageNamed:@"placeholder.png"]
options:SDWebImageRefreshCached
completed: nil];
Cheers!
The problem with SDImageCache's aging (which now has a setter: maxCacheAge) is that SDWebImage never really proactively does anything with it. You need to invoke cleanDisk yourself at some point to purge old data from the cache. Note: SDWebImage does invoke cleanDisk when the app terminates, but apps are not guaranteed to get a termination notification from the OS.
As I read in the SDWeb readme in git, It might help:
In your case, you may use the SDWebImageRefreshCached
flag. This will slightly degrade the performance but will respect the HTTP caching control headers:
[imageView sd_setImageWithURL:[NSURL URLWithString:@"https://graph.facebook.com/olivier.poitrey/picture"]
placeholderImage:[UIImage imageNamed:@"avatar-placeholder.png"]
options:SDWebImageRefreshCached];
I had a look at the source code. It processes the setImageWithURL
method like this:
There is no request sent to ask the remote server if there is a new version while there is something old on disk, like using ETags of the HTTP protocol.
Digging a bit deeper the cache time is set to a static value in SDImageCache.m
static NSInteger cacheMaxCacheAge = 60*60*24*7; // 1 week
it cannot be changed with a setter.
So as long as the image in the cache is valid the SDWebImage
lib won't download anything new. After a week it'll download your changed image.
Incase you are looking to change the default cache duration in Swift. Set this in your AppDelegate.
Version 3:
SDWebImageManager.sharedManager().imageCache.maxCacheAge = CACHE_TIME_IN_SECONDS
Version 4:
SDWebImageManager.shared().imageCache?.config.maxCacheAge = CACHE_TIME_IN_SECONDS
-
I believe this only effects images that are caches after this value is set. IE if your app cache an image with the default cache expiration and then change it something else, your images will still only expire after a week. An easily solution to this is to just clear your cache.