Empty the cache programmatically in iOS

Stefan S picture Stefan S · Jul 10, 2013 · Viewed 9.4k times · Source

Does anyone by coincidence know how I can empty the cache memory of the iOS app that I am developing, in the moment it goes to the background (applicationDidEnterBackground)? I have investigated about NSCache but I am still not able to understand how could I retrieve the cache to basically remove/free it?

Answer

Alfie Hanssen picture Alfie Hanssen · Jul 10, 2013

Is this what you're talking about?

[[NSURLCache sharedURLCache] removeAllCachedResponses];

You can also modify the cache behavior of your requests to selectively cache responses. If you're using AFNetworking by chance, you can use setCacheResponseBlock. E.g. in one project I set it to return nil for all large video and audio files. But allow it to cache smaller image files.

[streamingOperation setCacheResponseBlock:^NSCachedURLResponse *(NSURLConnection *connection, NSCachedURLResponse *cachedResponse) {
    return nil; // Ensures we are not unecessarily caching asset data to Cache.db
}];