In my project I'm using AFNetworking for downloading data from the web. I'm leveraging NSURLRequestUseProtocolCachePolicy
on my NSURLRequest
to serve user cached data (if 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 types 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
{
// creating NSURL to give to NSURLRequest
NSURL *theURL = [NSURL URLWithString:URL];
//adding service version in http header
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:theURL];
[request addValue:HTTP_HEADER_VERSION_VALUE forHTTPHeaderField:HTTP_HEADER_VERSION_NAME];
//returing request
return request;
}
Now I would like to transition to new logic:
So basically I would like to serve cached data but check if my cached data is still valid on the server or if there's new data to download. Is there a way to achieve this? I tried with setCacheResponseBlock
on AFHTTPRequestOperation
but I can't get cached data timestamp. Is there a "smarter" way to do this?
Check out AFNetworking : How to know if response is using cache or not ? 304 or 200
"I found a way by saving modification-date associate with the request, and I compare this date when AFNetWorking answers to me.
not as clean as I intend, but works..."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With