Search code examples
ioscachingamazon-s3sdwebimage

Ignore query params with SDWebImage


I'm using SDWebImage to cache images in my app, however I recently ran into a problem where images that should be cached keep refreshing. Looking into it I found that the full image url from AWS is actually changing due to parameters tacked onto the end of the url. Every time I fetch the object that contains the image url, the image url returns with a dynamic "signature" and "expires" parameter (for security purposes). A different url so far as the image cache is concerned, but notice the same path to the image.

First fetch:

https://myapp.s3.amazonaws.com/path/image123.jpeg?AWSAccessKeyId=SOMEKEY&Signature=vrUFlMFEQ9fqQ%3D&Expires=1441702633

Fetch again 1 second later:

https://myapp.s3.amazonaws.com/path/image123.jpeg?AWSAccessKeyId=SOMEKEY&Signature=2mcMxUJLyJd7E%3D&Expires=1441703105

What's the best way to handle this situation? Sure would be awesome if SDWebImage had an option to ignore query params beyond the path to the file.


Solution

  • SDWebImage has a method that allows for using a custom key, which helps in this case as AWS changes the query every time it's called.

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary    *)launchOptions
    {
        SDWebImageManager.sharedManager.cacheKeyFilter = ^(NSURL *url) {
            url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path];
            return [url absoluteString];
        };
    
        // Your app init code...
        return YES;
    }
    

    For more reading: SDWebImage | Using the cache key filter