简单封装 AFNetworking
并添加缓存
初始化缓存 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*1024
diskPath:diskPath];
});
return sharedCache;
}
定义一个继承NSObject
的工具类,目的是方便以后换底层的网络库
+(void)getCacheWithUrl:(NSString *)url option:(BcRequestCenterCachePolicy)option parameters:(NSDictionary *)parameters success:(BaseHttpToolSucess)success failur:(BaseHttpToolFailur)failur
下面是实现的代码,我这里采用如果第一次进入没有缓存,那么直接读取服务器,如果本地有了,再存下来,每次读的都是上一次的数据,根据判断URL
实现
拿到request
NSString *url = nil;
NSError *serializationError = nil;
NSString *URLString = [[NSURL URLWithString:url relativeToURL:nil] absoluteString];
NSMutableURLRequest *request = [mgr.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:NSJSONReadingMutableLeaves
error:nil];
NSLog(@"缓存后的数据 %@",json);
}
当网络请求成功以后,判断一下之前是否存在这个URL
if (![operation.response.URL isEqual:cachedResponse.response.URL]) {
if (sucess) {
sucess(responseObject);
NSLog(@"第一次进入系统没有缓存%@",responseObject);
}
}
然后再保存下来
NSData *data = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:operation.response
data:data
userInfo:nil
storagePolicy:NSURLCacheStorageAllowed];
[[self sharedCache] storeCachedResponse:cachedResponse forRequest:request];
Demo: https://github.com/BaiCanLin/GETPOST
网友评论