【问题标题】:Alamofire/NSURLSession caching with private Cache-Control and max-age带有私有 Cache-Control 和 max-age 的 Alamofire/NSURLSession 缓存
【发布时间】:2018-03-14 15:27:00
【问题描述】:

我不确定我是否做错了什么,但是在设置 urlRequest.cachePolicy = .useProtocolCachePolicy 并将缓存头设置为私有且 max-age "Cache-Control" = "private, max-age=86400"; 时缓存不起作用

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

【问题讨论】:

    标签: ios swift alamofire nsurlsession nsurlrequest


    【解决方案1】:

    我尝试了以下对我来说效果很好的代码, 使用 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];
    

    【讨论】:

      猜你喜欢
      • 2015-10-19
      • 2019-01-17
      • 2018-10-06
      • 2018-11-24
      • 1970-01-01
      • 2011-12-08
      • 2019-07-09
      • 2020-08-11
      • 1970-01-01
      相关资源
      最近更新 更多