iOS网络请求中缓存技术用到了NSURLCache类,默认支持支持内存缓存和硬盘缓存。NSURLCache对NSURLRequest及其对应的NSCachedURLResponse缓存,并存放到本地数据库中。(就是说只要你使用NSURLRequest做网络请求,系统默认使用NSURLCache帮你做缓存)
NSURLCache的常见方法
1)获得全局缓存对象(没必要手动创建)NSURLCache*cache = [NSURLCache sharedURLCache];
2)设置内存缓存的最大容量(字节为单位,默认为512KB)- (void)setMemoryCapacity:(NSUInteger)memoryCapacity;
3)设置硬盘缓存的最大容量(字节为单位,默认为10M)- (void)setDiskCapacity:(NSUInteger)diskCapacity;
4)硬盘缓存的位置:沙盒/Library/Caches
5)取得某个请求的缓存-(NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request;
6)清除某个请求的缓存-(void)removeCachedResponseForRequest:(NSURLRequest *)request;
7)清除所有的缓存-(void)removeAllCachedResponses;
代码演示:
-(IBAction)post:(id)sender{
NSURLCache *cache = [NSURLCache sharedURLCache];
// 1.创建请求
NSURL *url = [NSURLURLWithString:@"http://api1.zhimamei.com/appProductSearch"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSCachedURLResponse *response = [cachecachedResponseForRequest:request];
if (response) {
NSLog(@"这个请求已经存在缓存");
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response.response;
NSString *string =[httpResponse.allHeaderFields objectForKey:@"Date"];
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"en_CN"]];
[inputFormatter setDateFormat:@"EEE, d MMM yyyy HH:mm:ss Z"];
NSDate* inputDate = [inputFormatter dateFromString:string];
NSDate *now = [NSDate date];
//判断缓存是否过期:超过两小时
if ([now timeIntervalSinceDate:inputDate] > 2 * 60 * 60 ) {
NSURLCache *cache = [NSURLCache sharedURLCache];
[cache removeCachedResponseForRequest:request];
//设置缓存策略:忽略缓存,重新请求
request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
}else{
//设置缓存策略:有缓存就用缓存,没有缓存就不发请求,当做请求出错处理(用于离线模式)
request.cachePolicy = NSURLRequestReturnCacheDataDontLoad;
}
}else {
NSLog(@"这个请求没有缓存");
}
//发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueuemainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError*connectionError) {
if (data) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:dataoptions:NSJSONReadingMutableLeaves error:nil];
NSLog(@"%@", dict);
}
}];
}