NSURLCache 提供的是内存以及磁盘的综合缓存机制。
NSURLCache 会将数据缓存到沙盒路径下的 Library/Caches 中,通过请求的 url+参数 来作为 key 储存的。
1.方法
获得全局缓存对象
NSURLCache *cache = [NSURLCache sharedURLCache];
设置内存缓存的最大容量(字节为单位,默认为512KB)
- (void)setMemoryCapacity:(NSUInteger)memoryCapacity;
设置硬盘缓存的最大容量(字节为单位,默认为10M)
- (void)setDiskCapacity:(NSUInteger)diskCapacity;
取得某个请求的缓存
- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request;
清除某个请求的缓存
- (void)removeCachedResponseForRequest:(NSURLRequest *)request;
清除所有的缓存
- (void)removeAllCachedResponses;
2.缓存策略
NSURLRequest 提供了 7 种缓存策略:
- NSURLRequestUseProtocolCachePolicy 默认的缓存策略(取决于协议)
- NSURLRequestReloadIgnoringLocalCacheData 忽略缓存,重新请求
- NSURLRequestReloadIgnoringLocalAndRemoteCacheData 未实现
- NSURLRequestReloadIgnoringCacheData = NSURLRequestReloadIgnoringLocalCacheData 忽略缓存,重新请求
- NSURLRequestReturnCacheDataElseLoad 有缓存就用缓存,没有缓存就重新请求
- NSURLRequestReturnCacheDataDontLoad 有缓存就用缓存,没有缓存就不发请求,当做请求出错处理(用于离线模式)
- NSURLRequestReloadRevalidatingCacheData 未实现
3.简单使用
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSURL *url = [NSURL URLWithString:@""];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
}];
[task resume];
}
/**
// 定期处理缓存
// if (缓存没有达到7天) {
// request.cachePolicy = NSURLRequestReturnCacheDataElseLoad;
// }
// 获得全局的缓存对象
NSURLCache *cache = [NSURLCache sharedURLCache];
// if (缓存达到7天) {
// [cache removeCachedResponseForRequest:request];
// }
// lastCacheDate = 2014-06-30 11:04:30
NSCachedURLResponse *response = [cache cachedResponseForRequest:request];
if (response) {
NSLog(@"---这个请求已经存在缓存");
} else {
NSLog(@"---这个请求没有缓存");
}
*/











网友评论