OGeek|极客世界-中国程序员成长平台

标题: ios - 带有私有(private) Cache-Control 和 max-age 的 Alamofire/NSURLSession 缓存 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:53
标题: ios - 带有私有(private) Cache-Control 和 max-age 的 Alamofire/NSURLSession 缓存

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

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



Best Answer-推荐答案


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

关于ios - 带有私有(private) Cache-Control 和 max-age 的 Alamofire/NSURLSession 缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46544473/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4