In my project, I use AFNetworking to download data from the Internet. I am using NSURLRequestUseProtocolCachePolicy on my NSURLRequest to serve cached user data (if the cache is valid). This is my code:
Request Method:
// create NSURL request NSURLRequest *request = [ServerFactory URLGETRequestWithURL:url]; //creating AFHTTPRequestOperation AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; //set serializaer operation.responseSerializer = [AFJSONResponseSerializer serializer]; //need to specify that text is acceptable content type, otherwise the error occurs operation.responseSerializer.acceptableContentTypes = [MyRepository acceptableContentTypes]; //running fetch request async [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { //parse data } failure:^(AFHTTPRequestOperation *operation, NSError *error) { //error handling }]; //start async operation [operation start];
Acceptable Content Type Method
+ (NSSet *)acceptableContentTypes { return [NSSet setWithObjects:@"application/json", @"text/plain", @"text/html" ,nil]; }
ServerFactory get methods
+ (NSURLRequest *)URLGETRequestWithURL:(NSString *)URL { NSMutableURLRequest *request = [[ServerFactory URLRequestWithURL:URL] mutableCopy]; [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; [request setHTTPMethod:@"GET"]; return request; } + (NSURLRequest *)URLRequestWithURL:(NSString *)URL {
Now I would like to move on to the new logic:
- Get cached data
- If the cached data is valid
- Serve user with cached data
- Sending a new request with the If-Modified-Since header set to get the cached data timestamp
- Server responds 304 Not changed if the cache is still OK, or 200 OK if there is new data
- Update user interface with new data
- If cache data has expired
- Get new data from the Internet
So basically I would like to serve cached data, but check if my cached data is saved on the server or if there is new data to load. Is there any way to achieve this? I tried with setCacheResponseBlock on AFHTTPRequestOperation , but I cannot get the timestamp of the cached data. Is there a more βsensibleβ way to do this?
source share