Q:

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.

A:

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

A:

@John 's answer is very good, but I met sometimes crashed.
below is more stable version.
SDWebImageManager.sharedManager.cacheKeyFilter = ^(NSURL *url) {
    if( [[url absoluteString] isEqualToString:@""] ){
        return @"";
    }
    url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path];
    return [url absoluteString];
};

This additional code checks if url is valid. [[NSURL alloc] initWithString:@""] or something like this makes crashes.

A:

The answer for Swift language:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    ...............

    SDWebImageManager.sharedManager().cacheKeyFilter = { url in
        if url.absoluteString == "" {
            return ""
        }

        let newUrl = NSURL(scheme: url.scheme, host: url.host, path: url.path!)!
        return newUrl.absoluteString
    }

    return true
}

