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];
为什么反复执行这段代码都没有直接从缓存中读出数据,而是都是到服务器去读的
---这个请求没有缓存
---从缓存获取,没有缓存就从服务器请求获取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
对照时间信息,后面都是从缓存取的。