SDWebImage - avoid clearing image cache on entering background

2.1k views Asked by At

I use SDWebImage in my app to load and cache images from the web. It works like a charm, but the only issue is that whenever I exit my app, even momentarily, the image cache gets cleared and all the images have to be downloaded again. This is especially a problem when the Internet connection is slow. I would like the images to be retained when I return to the app. Does anyone know how to achieve this?

2

There are 2 answers

1
OneSman7 On BEST ANSWER

Go to SDImageCache.m and seek method - (id)initWithNamespace:(NSString *)ns There you will find such code:

// Subscribe to app events
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(clearMemory)
                                                 name:UIApplicationDidReceiveMemoryWarningNotification
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(cleanDisk)
                                                 name:UIApplicationWillTerminateNotification
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(backgroundCleanDisk)
                                                 name:UIApplicationDidEnterBackgroundNotification
                                               object:nil];

Feel free to comment out or change anything if you want. I'd make an option to turn off these lines of code.

0
limboy On

make sure you don't set the maxCacheSize of [SDImageCache sharedImageCache], if it is set when the app go to background, it will clear cache files to fit the maxCacheSize.

in cleanDisk method, you can see there is a check before removing files

if (self.maxCacheSize > 0 && currentCacheSize > self.maxCacheSize)
{
// ...
}

so if maxCacheSize is not set, it will do nothing.