簡(jiǎn)單封裝 AFNetworking
并添加緩存
初始化緩存 10M內(nèi)存 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;
}
定義一個(gè)繼承NSObject
的工具類,目的是方便以后換底層的網(wǎng)絡(luò)庫(kù)
+(void)getCacheWithUrl:(NSString *)url option:(BcRequestCenterCachePolicy)option parameters:(NSDictionary *)parameters success:(BaseHttpToolSucess)success failur:(BaseHttpToolFailur)failur
下面是實(shí)現(xiàn)的代碼,我這里采用如果第一次進(jìn)入沒有緩存,那么直接讀取服務(wù)器拾因,如果本地有了粱坤,再存下來辈毯,每次讀的都是上一次的數(shù)據(jù)陨舱,根據(jù)判斷URL
實(shí)現(xiàn)
拿到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
械荷,轉(zhuǎn)換成JSON
NSCachedURLResponse *cachedResponse = [[self sharedCache] cachedResponseForRequest:request];
if (cachedResponse) {
id json = [NSJSONSerialization JSONObjectWithData:cachedResponse.data
options:NSJSONReadingMutableLeaves
error:nil];
NSLog(@"緩存后的數(shù)據(jù) %@",json);
}
當(dāng)網(wǎng)絡(luò)請(qǐng)求成功以后共耍,判斷一下之前是否存在這個(gè)URL
if (![operation.response.URL isEqual:cachedResponse.response.URL]) {
if (sucess) {
sucess(responseObject);
NSLog(@"第一次進(jìn)入系統(tǒng)沒有緩存%@",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
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者