Manage AFNetworking Cache and Responses

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 { // 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 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?

+6
source share
1 answer

Check out AFNetworking: how do I know if a response uses a cache or not? 304 or 200

"I found a way by storing the date associated with the change date with the request, and I compare that date when AFNetWorking answers me.

not as clean as I guess, but it works ... "

+1
source

Source: https://habr.com/ru/post/957256/


All Articles