ios - NSURLCache 问题
迷茫
迷茫 2017-04-17 13:48:37
[iOS讨论组]
     NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    config.requestCachePolicy = NSURLRequestReturnCacheDataElseLoad;
     NSURLCache *cache = [[NSURLCache alloc] initWithMemoryCapacity:10 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:@"big.urlcache"];
    config.URLCache = cache;
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://nshipster.com/nsurlcache/"]];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error) {
            NSLog(@"%@",error);
        }else{
            NSString *tempStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@",tempStr);
        }
    }];
    [task resume];

为什么反复执行这段代码都没有直接从缓存中读出数据,而是都是到服务器去读的

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回复(1)
PHPz
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.requestCachePolicy = NSURLRequestReturnCacheDataElseLoad;
NSURLCache *cache = [[NSURLCache alloc] initWithMemoryCapacity:10 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:@"big.urlcache"];
config.URLCache = cache;
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://nshipster.com/nsurlcache/"]];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
     NSLog(@"---从缓存获取,没有缓存就从服务器请求获取%@",[(NSHTTPURLResponse*)response allHeaderFields][@"Date"]);
}];
[task resume];

NSCachedURLResponse *response = [cache cachedResponseForRequest:request];

if (response) {
            NSLog(@"---有缓存%@",[(NSHTTPURLResponse*)response.response allHeaderFields][@"Date"]);
    
} else {
    NSLog(@"---这个请求没有缓存");
}

---这个请求没有缓存
---从缓存获取,没有缓存就从服务器请求获取Wed, 01 Jun 2016 01:50:21 GMT
---这个请求没有缓存
---从缓存获取,没有缓存就从服务器请求获取Wed, 01 Jun 2016 01:50:24 GMT
---有缓存Wed, 01 Jun 2016 01:50:21 GMT
---从缓存获取,没有缓存就从服务器请求获取Wed, 01 Jun 2016 01:50:21 GMT
---有缓存Wed, 01 Jun 2016 01:50:21 GMT
---从缓存获取,没有缓存就从服务器请求获取Wed, 01 Jun 2016 01:50:21 GMT

对照时间信息,后面都是从缓存取的。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号