I'm using AFNetworking and need to cache data in one response for a several minutes. So I set NSUrlCache in app delegate and then in my request setting up it:
NSMutableURLRequest *request = //obtain request;
request.cachePolicy = NSURLRequestReturnCacheDataElseLoad;
How then set expiration date: if the data was loaded more than n minutes ago, ask response from server and not from disk?
EDIT:
Assume that server doesn't support caching, I need to manage it in code.
The expiration of responses in the
NSURLCache
is controlled via theCache-Control
header in the HTTP response.EDIT I see you've updated your question. If the server doesn't provide the Cache-Control header in the response, it won't be cached. Every request to that endpoint will load the endpoint rather than return a cached response.
Swift equivalent of @HotJard's solution using URLSession
Then implement URLSessionDataDelegate protocol in your custom class
Don't forget to create your configuration and session, passing in the your custom class as the delegate reference e.g.
So, I found the solution.
The idea is to use
connection:willCacheResponse:
method. Before cache the response it will be executed and there we can change response and return new, or return nil and the response will not be cached. As I use AFNetworking, there is a nice method in operation:Add code:
Where
responseWithExpirationDuration
from category:So, we set expiration in seconds in http header according to http/1.1 For that we need one of headers to be set up: Expires, Cache-Control: s-maxage or max-age Then create new cache response, because the properties is read only, and return new object.