Alamofire / NSURLSession缓存,具有私有Cache-Control和max-age

时间:2017-10-03 12:20:09

标签: ios swift alamofire nsurlsession nsurlrequest

我不确定自己是否做错了什么,但在设置urlRequest.cachePolicy = .useProtocolCachePolicy并将缓存标头设置为私有时使用max-age "Cache-Control" = "private, max-age=86400";,缓存无法正常工作

useProtocolCachePolicy应该与private一起使用吗?或者我需要手动将其覆盖为公开?

1 个答案:

答案 0 :(得分:0)

我尝试了以下对我来说很好的代码, 使用cachePolicy:NSURLRequestUseProtocolCachePolicy。

根据http标头响应中的cache-control / max-age使缓存过期:

我使用了这个有用的blog

这是我使用的代码:

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];