首页 > NSURLCache 问题

NSURLCache 问题

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

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


    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

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

【热门文章】
【热门文章】