iOS中的NSURLCache数据缓存类用法解析
在IOS应用程序开发中,为了减少与服务端的交互次数,加快用户的响应速度,一般都会在IOS设备中加一个缓存的机制。使用缓存的目的是为了使用的应用程序能更快速的响应用户输入,是程序高效的运行。有时候我们需要将远程web服务器获取的数据缓存起来,减少对同一个url多次请求。下面将介绍如何在IOS设备中进行缓存。
内存缓存我们可以使用sdk中的NSURLCache类。NSURLRequest需要一个缓存参数来说明它请求的url何如缓存数据的,我们先看下它的CachePolicy类型。
1、NSURLRequestUseProtocolCachePolicyNSURLRequest默认的cachepolicy,使用Protocol协议定义。
2、NSURLRequestReloadIgnoringCacheData忽略缓存直接从原始地址下载。
3、NSURLRequestReturnCacheDataElseLoad只有在cache中不存在data时才从原始地址下载。
4、NSURLRequestReturnCacheDataDontLoad只使用cache数据,如果不存在cache,请求失败;用于没有建立网络连接离线模式;
5、NSURLRequestReloadIgnoringLocalAndRemoteCacheData:忽略本地和远程的缓存数据,直接从原始地址下载,与NSURLRequestReloadIgnoringCacheData类似。
6、NSURLRequestReloadRevalidatingCacheData:验证本地数据与远程数据是否相同,如果不同则下载远程数据,否则使用本地数据。
一些常用方法与属性:
//获取当前应用的缓存管理对象
+(NSURLCache*)sharedURLCache;
//设置自定义的NSURLCache作为应用缓存管理对象
+(void)setSharedURLCache:(NSURLCache*)cache;
//初始化一个应用缓存对象
/*
memoryCapacity设置内存缓存容量
diskCapacity设置磁盘缓存容量
path磁盘缓存路径
内容缓存会在应用程序退出后清空磁盘缓存不会
*/
-(instancetype)initWithMemoryCapacity:(NSUInteger)memoryCapacitydiskCapacity:(NSUInteger)diskCapacitydiskPath:(nullableNSString*)path;
//获取某一请求的缓存
-(nullableNSCachedURLResponse*)cachedResponseForRequest:(NSURLRequest*)request;
//给请求设置指定的缓存
-(void)storeCachedResponse:(NSCachedURLResponse*)cachedResponseforRequest:(NSURLRequest*)request;
//移除某个请求的缓存
-(void)removeCachedResponseForRequest:(NSURLRequest*)request;
//移除所有缓存数据
-(void)removeAllCachedResponses;
//移除某个时间起的缓存设置
-(void)removeCachedResponsesSinceDate:(NSDate*)dateNS_AVAILABLE(10_10,8_0);
//内存缓存容量大小
@propertyNSUIntegermemoryCapacity;
//磁盘缓存容量大小
@propertyNSUIntegerdiskCapacity;
//当前已用内存容量
@property(readonly)NSUIntegercurrentMemoryUsage;
//当前已用磁盘容量
@property(readonly)NSUIntegercurrentDiskUsage;
简单例子:
#import
@interfaceViewController:UIViewController
@property(strong,nonatomic)NSURLConnection*connection;
@property(strong,nonatomic)NSURLCache*urlCache;
@property(strong,nonatomic)NSURL*url;
@property(strong,nonatomic)NSMutableURLRequest*request;
-(IBAction)reloadWebView:(UIButton*)sender;
@end
#import"ViewController.h"
@interfaceViewController()
@end
@implementationViewController
-(void)viewDidLoad
{
[superviewDidLoad];
NSString*paramURLAsString=@"http://blog.sina.com.cn/u/2526279194";
self.urlCache=[NSURLCachesharedURLCache];
[self.urlCachesetMemoryCapacity:1*1024*1024];
//创建一个nsurl
self.url=[NSURLURLWithString:paramURLAsString];
//创建一个请求
self.request=[NSMutableURLRequestrequestWithURL:self.url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0f];
[self.myWebViewloadRequest:self.request];
}
这个例子中,我们请求url为http://blog.sina.com.cn/u/2526279194的网站。如果这个url被缓存了,我们直接从缓存中获取数据,否则从http://blog.sina.com.cn/u/2526279194站点上重新获取数据。我们设置了缓存大小为1M。
-(IBAction)reloadWebView:(UIButton*)sender{
//从请求中获取缓存输出
NSCachedURLResponse*response=[self.urlCachecachedResponseForRequest:self.request];
//判断是否有缓存
if(response!=nil){
NSLog(@"如果有缓存输出,从缓存中获取数据");
[self.requestsetCachePolicy:NSURLRequestReturnCacheDataDontLoad];
}
[self.myWebViewloadRequest:self.request];
self.connection=nil;
NSURLConnection*newConnection=[[NSURLConnectionalloc]initWithRequest:self.request
delegate:self
startImmediately:YES];
self.connection=newConnection;
}
使用下面代码,我将请求的过程打印出来
-(void) connection:(NSURLConnection*)connection
didReceiveResponse:(NSURLResponse*)response{
NSLog(@"将接收输出");
}
-(NSURLRequest*)connection:(NSURLConnection*)connection
willSendRequest:(NSURLRequest*)request
redirectResponse:(NSURLResponse*)redirectResponse{
NSLog(@"即将发送请求");
return(request);
}
-(void)connection:(NSURLConnection*)connection
didReceiveData:(NSData*)data{
NSLog(@"接受数据");
NSLog(@"数据长度为=%lu",(unsignedlong)[datalength]);
}
-(NSCachedURLResponse*)connection:(NSURLConnection*)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse{
NSLog(@"将缓存输出");
return(cachedResponse);
}
-(void)connectionDidFinishLoading:(NSURLConnection*)connection{
NSLog(@"请求完成");
}
-(void)connection:(NSURLConnection*)connection
didFailWithError:(NSError*)error{
NSLog(@"请求失败");
}
@end
第一次打印结果如下
2013-01-3115:28:29.923NSURLCacheDemo[27848:907]即将发送请求 2013-01-3115:28:30.043NSURLCacheDemo[27848:907]将接收输出 2013-01-3115:28:30.045NSURLCacheDemo[27848:907]接受数据 2013-01-3115:28:30.047NSURLCacheDemo[27848:907]数据长度为=30047 2013-01-3115:28:30.095NSURLCacheDemo[27848:907]接受数据 2013-01-3115:28:30.098NSURLCacheDemo[27848:907]数据长度为=3575 2013-01-3115:28:30.102NSURLCacheDemo[27848:907]接受数据 2013-01-3115:28:30.104NSURLCacheDemo[27848:907]数据长度为=1482 2013-01-3115:28:30.105NSURLCacheDemo[27848:907]将缓存输出 2013-01-3115:28:30.107NSURLCacheDemo[27848:907]请求完成
第二次点击打印结果如下
2013-01-3115:28:31.599NSURLCacheDemo[27848:907]如果有缓存输出,从缓存中获取数据 2013-01-3115:28:31.607NSURLCacheDemo[27848:907]即将发送请求 2013-01-3115:28:31.840NSURLCacheDemo[27848:907]将接收输出 2013-01-3115:28:31.843NSURLCacheDemo[27848:907]接受数据 2013-01-3115:28:31.845NSURLCacheDemo[27848:907]数据长度为=35104 2013-01-3115:28:31.846NSURLCacheDemo[27848:907]请求完成
我们看到没有“将缓存输出”一项,请求到的数据是第一次请求的累积,也就是第二次是从内存中获取数据的。