NSURLCache使用有許多限制寝优,蘋(píng)果限制的笛谦。
1.只能用在get請(qǐng)求里面糕殉,post可以洗洗睡了。
2.緩存機(jī)制選擇 NSURLRequestReturnCacheDataElseLoad
有緩存從緩存取數(shù)據(jù)驹针,沒(méi)有緩存從網(wǎng)絡(luò)取數(shù)據(jù)。
3.需要服務(wù)器定義數(shù)據(jù)是否發(fā)生變化诀艰,allHeaderFields里可以查找到是否修改了的信息柬甥。公司服務(wù)器沒(méi)有定義的話,就不能夠判斷讀取的緩存數(shù)據(jù)是否需要刷新其垄。
4.原先網(wǎng)絡(luò)請(qǐng)求的回調(diào)會(huì)被緩存結(jié)果代替苛蒲,意思:有緩存的情況下根本不會(huì)去網(wǎng)絡(luò)獲取數(shù)據(jù),返回的都是緩存結(jié)果,除非服務(wù)器allHeaderFields數(shù)據(jù)發(fā)生了變化——-大坑绿满,所以會(huì)變動(dòng)的數(shù)據(jù)就盡量不要用這種方式請(qǐng)求了臂外。一般也應(yīng)用于離線閱讀,不會(huì)改變數(shù)據(jù)的地方喇颁。
5.刪除緩存的removeCachedResponseForRequest 這個(gè)方法是無(wú)效的.所以緩存是不會(huì)被刪除的—只有刪除全部緩存才有效—————————————————————
6.相關(guān)資料很少:這是摸坑后可以跑的內(nèi)容漏健,不能刪除對(duì)應(yīng)緩存沒(méi)有什么意義。
NSURL*url = [NSURLURLWithString:@"www.abc.com"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];// 2.設(shè)置緩存策略(有緩存就用緩存橘霎,沒(méi)有緩存就重新請(qǐng)求)request.cachePolicy= NSURLRequestReturnCacheDataElseLoad;
request.timeoutInterval=60.0f;// 3.發(fā)送請(qǐng)求[NSURLConnectionsendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data,NSError*connectionError) {if(data) {//? ? ? ? ? ? ? ? ? NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];//? NSLog(@"%@", dict);NSLog(@"---從緩存獲取蔫浆,沒(méi)有緩存就從服務(wù)器請(qǐng)求獲取%@",[(NSHTTPURLResponse*)response allHeaderFields][@"Date"]);
}
}];
NSURLCache *cache = [NSURLCache sharedURLCache];
NSCachedURLResponse *response = [cache cachedResponseForRequest:request];
if(response) {//緩存時(shí)間信息NSDate*cachesDate= [NSDatedateFromRFC822String:[(NSHTTPURLResponse*)response.responseallHeaderFields][@"Date"]];//當(dāng)前時(shí)間[NSDategetCurrentTimeFromWeb:^(NSDate*currentTime) {NSTimeIntervalsecondsInterval= [currentTime timeIntervalSinceDate:cachesDate];NSLog(@"secondsInterval=? %lf秒",secondsInterval);if(secondsInterval<=15.0) {
request.cachePolicy= NSURLRequestReturnCacheDataElseLoad;NSLog(@"---無(wú)需刪除緩存%@",[(NSHTTPURLResponse*)response.responseallHeaderFields][@"Date"]);
}//時(shí)間超過(guò),過(guò)期if(secondsInterval>15.0) {
[cache removeAllCachedResponses];NSLog(@"---刪除緩存%@",[(NSHTTPURLResponse*)response.responseallHeaderFields][@"Date"]);
}
}];
}else{NSLog(@"---這個(gè)請(qǐng)求沒(méi)有緩存");
}
7.綜上所述姐叁,還是自己緩存吧瓦盛,這個(gè)nsurlcache沒(méi)什么鳥(niǎo)用,自己做一套寫(xiě)進(jìn)數(shù)據(jù)庫(kù)外潜,不知道好多少原环。
8.參考鏈接:
http://www.cnblogs.com/wendingding/p/3950198.html
http://stackoverflow.com/questions/25596424/nsurlcaches-removecachedresponseforrequest-has-no-effect
https://github.com/ChenYilong/ParseSourceCodeStudy/blob/master/02_Parse的網(wǎng)絡(luò)緩存與離線存儲(chǔ)/iOS網(wǎng)絡(luò)緩存掃盲篇.md
原文:http://blog.csdn.net/github_35041937/article/details/51545932