iOS NSURLCache
1.如果向同一個URL請求多次,返回的數據是一樣的,可以考慮用緩存,以提高響應速度,節省用戶流量
2.緩存的思路
客戶端發起請求之前,檢測內存緩存: a.內存緩存有數據,則使用內存緩存的數據
?b.內存緩存沒數據,則監測硬盤(沙盒)緩存: c.硬盤緩存有數據,則使用硬盤緩存
? ? ? ? d.硬盤緩存沒數據,則向服務器發請求獲取數據
3.緩存數據的過程
4.緩存的實現,一般是GET請求需要做數據緩存,POST請求不需要.
蘋果提供NSURLCache類專門處理數據緩存
5.NSURLCache的用法
5.1蘋果提供了一個全局的緩存對象,用于管理緩存
?NSURLCache *cache = [NSURLCache sharedURLCache];
? ? [cache setMemoryCapacity:1024 * 1024]; ?// 設置內存緩存容量=1M;如果不設置,默認=512KB
? ? [cache setDiskCapacity:20 * 1024 * 1024];?// 設置硬盤緩存容量=20M;如果不設置,默認=10M,硬盤緩存的位置沙盒/Library/Caches
5.2 網絡請求的示例代碼
?NSURL *url = [NSURL URLWithString:@"http://localhost/photo/1.png"];
? ? NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
? ? request.cachePolicy = NSURLRequestReturnCacheDataElseLoad; // 設置緩存策略
?
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
? ? ? ? ? ? if (data) {
? ? ? ? ? ? ? ? NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
? ? ? ? ? ? ? ? NSLog(@"%@",dict);
? ? ? ? ? ? }
? ? }];
注:request有cachePolicy屬性,cachePolicy是枚舉類型,實際上就"4"個枚舉值(2個未實現,1個重復)
? ??NSURLRequestUseProtocolCachePolicy = 0, ?//默認的緩存策略(取決于http協議)
? ? NSURLRequestReloadIgnoringLocalCacheData = 1, ?//忽略緩存,重新請求
? ? NSURLRequestReloadIgnoringLocalAndRemoteCacheData = 4, // Unimplemented,蘋果未實現
? ? NSURLRequestReloadIgnoringCacheData = NSURLRequestReloadIgnoringLocalCacheData, ?//忽略緩存,重新請求
? ? NSURLRequestReturnCacheDataElseLoad = 2, ?//如果有緩存就使用緩存,沒有就請求?
? ? NSURLRequestReturnCacheDataDontLoad = 3, ?//始終使用緩存,不請求,適用于應用的離線模式
? ? NSURLRequestReloadRevalidatingCacheData = 5, // Unimplemented,蘋果未實現
?
5.3 怎么使用NSURLCache管理緩存呢?
其實5.2里,已經用到了NSURLCache了, ?request默認的緩存對象就是這個[NSURLCache?sharedURLCache] 全局緩存對象.
下面5.3的代碼,演示可以利用NSURLCache判斷 XX請求是否有緩存
?NSURL *url = [NSURL URLWithString:@"http://localhost/photo/1.png"];
? ? NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
? ? request.cachePolicy = NSURLRequestReturnCacheDataElseLoad;?// 設置緩存策略
? ? NSURLCache *cache = [NSURLCache?sharedURLCache]; ?
? ? NSCachedURLResponse *response = [cache cachedResponseForRequest:request];
? ? if (response) {
? ? ? ? NSLog(@"該請求存在緩存");
? ? }else{
? ? ? ? NSLog(@"該請求不存在緩存");
}
?
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
? ? ? ? ? ? if (data) {
? ? ? ? ? ? ? ? NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
? ? ? ? ? ? ? ? NSLog(@"%@",dict);
? ? ? ? ? ? }
? ? }];
5.4 定期清除緩存
?#define weekTime 604800
?NSURL *url = [NSURL URLWithString:@"http://localhost/photo/1.png"];
? ? NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
? ? request.cachePolicy = NSURLRequestReturnCacheDataElseLoad;?// 設置緩存策略
?//發起請求之前,判斷當前時間距離最后緩存時間,是否大于7天
?NSDate *lastCacheTime = [[NSUserDefaults standardUserDefaults] objectForKey:@"lastCacheTime"];
if([[NSDate date] timeIntervalSinceDate:lastCacheTime] > weekTime){
? ? [ [NSURLCache sharedURLCache] ?removeAllCachedResponses ]; ?// 刪除所有緩存
?}
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
? ? ? ? ? ? if (data) {
? ? ? ? ? ? ? ? NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
? ? ? ? ? ? ? ? NSLog(@"%@",dict);
?[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"lastCacheTime"]; ?//把Now存儲為"最后緩存時間"
? ? ? ? ? ? }
? ? }];
補充: 還可以刪除具體的某個請求的緩存 ?[ [NSURLCache sharedURLCache] removeCachedResponseForRequest:(NSURLRequest *) ]
6 使用緩存的注意事項:
1>經常更新的數據,不能用緩存,例如股票,天氣預報
2>偶爾更新的數據,定期更改緩存策略,或清除緩存
3>大量使用緩存時,需要定期清除緩存
?
轉載于:https://www.cnblogs.com/oumygade/p/4245322.html
總結
以上是生活随笔為你收集整理的iOS NSURLCache的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 事件监听机制——鼠标事件MouseEve
- 下一篇: 寒假训练1解题报告