NSURLCache缓存使用简介
1.在IOS應(yīng)用程序開發(fā)中,為了減少與服務(wù)端的交互次數(shù),加快用戶的響應(yīng)速度,一般都會在IOS設(shè)備中加一個緩存的機制。使用緩存的目的是為了使用的應(yīng)用程序能更快速的響應(yīng)用戶輸入,是程序高效的運行。有時候我們需要將遠程web服務(wù)器獲取的數(shù)據(jù)緩存起來,減少對同一個url多次請求。使用sdk中的NSURLCache類,可以很方便的實現(xiàn)此功能。2.NSURLCache可以做到完全的離線緩存,即在沒有網(wǎng)絡(luò)的情況下打開離線內(nèi)容。通過自定義的實現(xiàn),將緩存文件存放到沙盒路徑下,緩存空間沒有大小限制。可以借鑒H5離線緩存中的Manifest文件,來定義緩存策略。Manifest文件從服務(wù)器端下載下來,在本地做版本對比,來實現(xiàn)存儲和更新。3.?NSURLCache攔截不到WKWebView中發(fā)出的任何網(wǎng)絡(luò)請求。所以如果使用WKWebView的話,NSURLCache實現(xiàn)不了離線緩存的功能。
二、一般使用場景
1.NSURLRequest需要一個緩存策略參數(shù)來說明它請求的url何如緩存數(shù)據(jù)的:CachePolicy類型。(1)NSURLRequestUseProtocolCachePolicy:NSURLRequest默認(rèn)的cache policy,使用Protocol協(xié)議定義。(2)NSURLRequestReloadIgnoringCacheData:忽略緩存直接從原始地址下載。(3)NSURLRequestReturnCacheDataElseLoad:只有在cache中不存在data時才從原始地址下載。(4)NSURLRequestReturnCacheDataDontLoad:只使用cache數(shù)據(jù),如果不存在cache,請求失敗;用于沒有建立網(wǎng)絡(luò)連接離線模式;(5)NSURLRequestReloadIgnoringLocalAndRemoteCacheData:忽略本地和遠程的緩存數(shù)據(jù),直接從原始地址下載,與NSURLRequestReloadIgnoringCacheData類似。?(6)NSURLRequestReloadRevalidatingCacheData:驗證本地數(shù)據(jù)與遠程數(shù)據(jù)是否相同,如果不同則下載遠程數(shù)據(jù),否則使用本地數(shù)據(jù)。(7)說明:5和6蘋果暫未實現(xiàn)。
2.首先我們需要在發(fā)送請求之前設(shè)置一下緩存大小:(1)默認(rèn)情況下,內(nèi)存是4M,4* 1024 * 1024;硬盤為20M,20 * 1024 * 1024;? [[NSURLCache sharedURLCache] setMemoryCapacity:4*1024*1024]。? [[NSURLCache sharedURLCache] setDiskCapacity:20*1024*1024]。?(2)也可以自己初始化緩存對象:? NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4*1024*1024 diskCapacity:20*1024*1024 diskPath:path];? [NSURLCache setSharedURLCache:URLCache];
3.控制需不需要緩存:NSURLConnectionDataDelegate代理方法中,下面的方法用來指定此次請求需不需要緩存,同時也可以在返回之前,修改response里面的數(shù)據(jù):- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
三、要點:
1.UIWebView的的NSURLRequest請求,以及自己用NSURLConnection發(fā)送的請求,NSURLCache都會攔截并存儲。2.NSURLCache只對異步請求有效。3.NSURLCache的緩存包括內(nèi)存緩存和磁盤緩存,iOS4.x系統(tǒng)只有內(nèi)存緩存,iOS5.x及以上兩者都有,但僅支持HTTP,HTTPS在iOS6中增加了支持。磁盤緩存有默認(rèn)的緩存路徑,也可以自己指定路徑。4.當(dāng)系統(tǒng)存儲空間不足時,當(dāng)前的請求不會被緩存,包括之前的磁盤緩存也可能被系統(tǒng)清除掉。5.如果有使用NSURLCache,在應(yīng)用收到內(nèi)存警告時,應(yīng)該清空緩存:removeAllCachedResponses。
四:NSURLCache相關(guān)API:
1.功能方法:(1)- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request;返回對應(yīng)的NSURLRequest緩存的response,如果沒有則返回nil。(2)- (void)storeCachedResponse:(NSCachedURLResponse *)cachedResponse forRequest:(NSURLRequest *)request;為特定的NSURLRequest指定緩存對象,并存儲。(3)- (void)removeCachedResponseForRequest:(NSURLRequest *)request; ?移除特定NSURLRequest的cache。(4)- (void)removeAllCachedResponses;移除所有的cache。?2.property方法- (NSUInteger)memoryCapacity;- (NSUInteger)diskCapacity;- (void)setMemoryCapacity:(NSUInteger)memoryCapacity;- (void)setDiskCapacity:(NSUInteger)diskCapacity;- (NSUInteger)currentMemoryUsage;- (NSUInteger)currentDiskUsage;
五、NSCachedURLResponse對象:包裝了一下系統(tǒng)緩存機制的對象,保持了緩存對象的個性和特性。
1. NSURLCacheStoragePolicy 緩存策略有三種enum{? ? NSURLCacheStorageAllowed,? ? NSURLCacheStorageAllowedInMemoryOnly,? ? NSURLCacheStorageNotAllowed,};?2. 構(gòu)造方法- (id)initWithResponse:(NSURLResponse *)response data:(NSData *)data;- (id)initWithResponse:(NSURLResponse *)response data:(NSData *)data userInfo:(NSDictionary *)userInfo storagePolicy:(NSURLCacheStoragePolicy)storagePolicy;?3. 相關(guān)API- (NSURLResponse *)response;- (NSData *)data;- (NSDictionary *)userInfo;- (NSURLCacheStoragePolicy)storagePolicy;
六、自定義NSURLCache
在一些特殊場景,如果要實現(xiàn)自定義的緩存機制,需要子類化NSURLCache。1.重寫cachedResponseForRequest:(NSURLRequest *)request,這個會在請求發(fā)送前會被調(diào)用,從中我們可以判定是否針對此NSURLRequest返回本地數(shù)據(jù)。如果本地沒有緩存就調(diào)用下面這條語句:return [super cachedResponseForRequest:request];2.重寫storeCachedResponse:(NSCachedURLResponse *)cachedResponse forRequest:(NSURLRequest *)request,我們可以對某一個請求做我們自己的數(shù)據(jù)保存機制,如果使用系統(tǒng)默認(rèn)的數(shù)據(jù)保存機制,則調(diào)用[super storeCachedResponse:cachedResponse forRequest:request];
七、自定義NSURLCache簡單示例:
- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request{
? ? //獲取URL整體路徑
? ? NSString *urlStringMD5 = [self md5:request.URL.absoluteString];
?? ?
? ? //獲取緩存文件存儲地址
? ? NSString *filePath = [[self getDocumentPath] stringByAppendingPathComponent:urlStringMD5];
?? ?
? ? //如果緩存存在,則返回緩存數(shù)據(jù),否則使用系統(tǒng)默認(rèn)處理
? ? if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
? ? ? ? //獲取緩存文件路徑
? ? ? ? NSData *fileData = [[NSData alloc] initWithContentsOfFile:filePath];
? ? ? ? //根據(jù)URL路徑,獲取媒體類型
? ? ? ? NSString *memiType = [self mimeTypeForPath:request.URL.absoluteString];
? ? ? ? //合成NSCachedURLResponse對象,返回
? ? ? ? NSURLResponse *response = [[NSURLResponse alloc] initWithURL:[request URL]
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? MIMEType:memiType
?? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? expectedContentLength:[fileData length]
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? textEncodingName:nil];
? ? ? ? NSCachedURLResponse *cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:response data:fileData];
? ? ? ? return cachedResponse;
? ? }else{
? ? ? ? return [super cachedResponseForRequest:request];
? ? }
}
- (void)storeCachedResponse:(NSCachedURLResponse *)cachedResponse forRequest:(NSURLRequest *)request{
? ? //將服務(wù)器返回數(shù)據(jù)緩存起來
? ? NSString *urlStringMD5 = [self md5:request.URL.absoluteString];
? ? NSString *filePath = [[self getDocumentPath] stringByAppendingPathComponent:urlStringMD5];
? ? [cachedResponse.data writeToFile:filePath atomically:YES];
}
總結(jié)
以上是生活随笔為你收集整理的NSURLCache缓存使用简介的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: XMPP扩展协议详解
- 下一篇: [配置中心] --- consul