Search code examples
iosiphoneweb-servicesnsurlcache

How to use NSURLCache with My Web service calls using NSURLSession


I am using Web service in my app with NSURLSession and Wanted to use the NSURLCache to cache my webservice call for speed optimization of app.And Also cache should be reload in background if any updates on server.

How I can achieve that ? Please suggest......


Solution

  • NSURLSession uses a cache by default, based on the standard protocol caching policy, which basically means that if the cache control headers allow it to be cached, if it hasn't expired, if it is a GET request, if the request is less than about 5% of the size of the cache, etc., it will cache it, and will use the cache when you request it again.

    However, it sounds like you also want to be able to clear the cache under programmatic control. To do that, first set the URLCache property on the session configuration to a newly allocated NSURLCache before you create the session.

    Later, when you want to clear the cache, just call the removeAllCachedResponses method on that cache object.

    Of course, the question is how you'll know if something has changed on the server, if you're caching all your requests. Chances are, you'll need to make at least some requests with caching disabled. The details are, of course, specific to what you're trying to do.