3

I'm not sure if I'm doing something wrong, but caching is not working when setting urlRequest.cachePolicy = .useProtocolCachePolicy and having a cache-header set to private with max-age "Cache-Control" = "private, max-age=86400";

Should useProtocolCachePolicy work with private? Or I need to manually override it to public?

vburojevic
  • 1,666
  • 5
  • 24
  • 34

1 Answers1

0

I tried following code which worked fine for me, using cachePolicy:NSURLRequestUseProtocolCachePolicy.

it expires the cache according to cache-control/max-age in http header response:

I used this helpful blog

here is the code I used:

NSURL * url = [NSURL URLWithString:@"https://yourserver.com"];

NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url
        cachePolicy:NSURLRequestUseProtocolCachePolicy
        timeoutInterval:60.0
    ];

    if (self.session == nil) {
        NSURLSessionConfiguration * config = [NSURLSessionConfiguration defaultSessionConfiguration];
        self.session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:NSOperationQueue.mainQueue];
    }
    NSURLSessionDataTask *task = [self.session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        if (error != nil) {
            NSLog(@"task transport error %@ / %d", error.domain, (int) error.code);
            return;
        }

        NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse*) response;
        NSLog(@"task finished with status %d, bytes %zu", (int) httpResponse.statusCode, (size_t) data.length);

        NSDictionary * headers = httpResponse.allHeaderFields;
        NSLog(@"response-headers %@",headers);
    }];

    [task resume];
michlv
  • 1
  • 1