6

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:

  • Get cached data
  • If cached data valid
    • Serve user with cached data
    • Dispatch new request with If-Modified-Since header set to retrieved cached data time stamp
    • Server respondes 304 Not Modified if cache is still OK, or 200 OK if there is new data
    • Update UI with new data
  • If cache data expired
    • Get new data from web

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?

Carl Veazey
  • 18,392
  • 8
  • 66
  • 81
paxx
  • 1,079
  • 2
  • 12
  • 26

1 Answers1

1

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..."

Community
  • 1
  • 1
pfrank
  • 2,090
  • 1
  • 19
  • 26