Search code examples
iosafnetworkingnsurlcache

AFNetworking 2.0 AFHTTPRequestOperationManager CachePolicy not working


I'm trying to make a GET request to a server with an If-Modified-Since header in order to avoid loading identical content. When I make a request I know that the server is sending back a 304 indicating that the content has not changed, but NSURLCache or AFNetworking is responding with a 200 with the cached content. In order to prevent this I set the request serializer's cache policy to NSURLRequestReloadIgnoringLocalCacheData, however this does not solve the problem.

- (void)getConfig {

    //Retrive the timeStamp at which the config was last updated
    NSDate *timeStamp = [[NSUserDefaults standardUserDefaults] objectForKey:@"lastGetConfigDate"];

    //Get the rfc1123 representation of the timeStamp
    NSString *dateString = [timeStamp rfc1123String];

    //If we're not force loading the data then include the time stamp in the If-modified-Since header
    [self.requestSerializer setValue:[NSString stringWithFormat:@"%@", dateString] forHTTPHeaderField:@"If-Modified-Since"];

    //Setting cachePolicy to ignore cache data to prevent the cached response
    [self.requestSerializer setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];

    //GET REQUEST to /api/config
    [self GET:@"/api/config" parameters:nil success: ^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *jsonDict = (NSDictionary *)responseObject;

        DDLogInfo(@"Config: 200");

        //If the config data was successfully loaded then set the lastGetConfigDate time stamp in the nsuserdefaults to send in the next call with the if-modified-since header
        if (success) {
            [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"lastGetConfigDate"];
        }

    } failure: ^(AFHTTPRequestOperation *operation, NSError *error) { ....

Solution

  • This is a bug in the latest version of AFNetworking, discussed in issue #2563. On January 24th, an attempt to resolve some other issue, this bug was introduced. To resolve it, either

    • roll back to a previous version of AFNetworking 2.5.0; or
    • manually post the KVO notifications yourself:

      [self.requestSerializer willChangeValueForKey:@"cachePolicy"];
      [self.requestSerializer setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
      [self.requestSerializer didChangeValueForKey:@"cachePolicy"];
      

    The lack of response regarding this bug is quite disappointing. Assuming this is indeed the issue you're suffering from (try one of the above and see if it remedies your problem), please join us and post your own comment in the discussion under issue #2563. The more people chime in on this, the more likely it is to be fixed.


    Note: This was fixed 26 March 2015 in commit 7d8e286.