AF缓存策略

2017-07-04  本文已影响43人  Demonboy

缓存的实现说明:由于GET请求一般用来查询数据,POST请求一般是发大量数据给服务器处理(变动性比较大),因此一般只对GET请求进行缓存,而不对POST请求进行缓存

AFURLRequestSerialization中的缓存属性
iOS对NSURLRequest提供了7种缓存策略:
1. NSURLRequestUseProtocolCachePolicy =0, 默认的缓存策略, 如果缓存不存在,直接从服务端获取。如果缓存存在,会根据response中的Cache-Control字段判断下一步操作,如: Cache-Control字段为must-revalidata, 则询问服务端该数据是否有更新,无更新的话直接返回给用户缓存数据,若已更新,则请求服务端
2. NSURLRequestReloadIgnoringLocalCacheData =1, 忽略本地缓存数据,直接请求服务端
3. NSURLRequestIgnoringLocalAndRemoteCacheData =4, 忽略本地缓存,代理服务器以及其他中介,直接请求源服务端,先判断是否有网
4. NSURLRequestReloadIgnoringCacheData = NSURLRequestReloadIgnoringLocalCacheData
5. NSURLRequestReturnCacheDataElseLoad =2, 有缓存就使用,不管其有效性(即忽略Cache-Control字段), 无则请求服务端
6. NSURLRequestReturnCacheDataDontLoad =3, 死活加载本地缓存. 没有就失败. (确定当前无网络时使用)
7. NSURLRequestReloadRevalidatingCacheData =5, 缓存数据必须得得到服务端确认有效才使用(貌似是NSURLRequestUseProtocolCachePolicy中的一种情况)
//每次请求之前先判断是否有网

if(!SYS_NETSTATE()) {

//无网 用缓存数据

manager.requestSerializer.cachePolicy = NSURLRequestReturnCacheDataDontLoad;

} else {

//有网用默认缓存策略
manager.requestSerializer.cachePolicy = NSURLRequestUseProtocolCachePolicy;
}   

上述不能满足缓存的话,可以自定义缓存策略,利用NSURLCache

初始化缓存10M内存  1g硬盘

static NSURLCache *sharedCache = nil; 

 +(NSURLCache *)sharedCache

{

static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{

NSString *diskPath = [NSString stringWithFormat:@"RequestCenter"];

sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:1024*1024*10 diskCapacity:1024*1024*1024diskPath:diskPath];});

return sharedCache;

}

下面是实现的代码,我这里采用如果第一次进入没有缓存,那么直接读取服务器,如果本地有了,再存下来,每次读的都是上一次的数据,根据判断URL实现

NSString *url =nil;

NSError *serializationError = nil;

NSString *URLString = [[NSURL URLWithString:url relativeToURL:nil] absoluteString];

拿到request

NSMutableURLRequest *request = [mananger.requestSerializer requestWithMethod:@"GET" URLString:URLString  parameters:parameters  error:&serializationError];

拿到cachedResponse,转换成JSON

NSCachedURLResponse *cachedResponse = [[self sharedCache] cachedResponseForRequest:request];

if(cachedResponse) {

id json = [NSJSONSerialization JSONObjectWithData:cachedResponse.data                                              options:NSJSONReadingMutableLeaveserror:nil];

NSLog(@"缓存后的数据  %@",json);

}

再请求成功之后缓存数据

NSData *data = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrintederror:nil];  

NSCachedURLResponse *cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:task.response  data:data                                                      userInfo:nil storagePolicy:NSURLCacheStorageAllowed];

[[self sharedCache] storeCachedResponse:cachedResponse forRequest:request];
上一篇 下一篇

猜你喜欢

热点阅读