建議先下載 Demo 跑跑看效果,GitHub 位址:STMURLCache(iOS 預加載 Web 頁面方案)。它可以一口氣預加載多個網址,接著把裝置切到離線狀態再逐一開啟,藉此驗證這些頁面是否真的被完整快取了起來。
在需要開啟預加載的位置建立實例:
self.sCache = [STMURLCache create:^(STMURLCacheMk *mk) { mk.whiteListsHost(whiteLists).whiteUserAgent(@"starming"); }];以下是全部可設置項目,預設值可直接查看 model 的 get 方法:
- (STMURLCacheMk *(^)(NSUInteger)) memoryCapacity; //內存容量 - (STMURLCacheMk *(^)(NSUInteger)) diskCapacity; //本地存儲容量 - (STMURLCacheMk *(^)(NSUInteger)) cacheTime; //緩存時間 - (STMURLCacheMk *(^)(NSString *)) subDirectory; //子目錄 - (STMURLCacheMk *(^)(BOOL)) isDownloadMode; //是否啟動下載模式 - (STMURLCacheMk *(^)(NSArray *)) whiteListsHost; //域名白名單 - (STMURLCacheMk *(^)(NSString *)) whiteUserAgent; //WebView的user-agent白名單 - (STMURLCacheMk *(^)(NSString *)) addHostWhiteList; //添加一個域名白名單 - (STMURLCacheMk *(^)(NSString *)) addRequestUrlWhiteList; //添加請求白名單 //NSURLProtocol相關設置 - (STMURLCacheMk *(^)(BOOL)) isUsingURLProtocol; //是否使用NSURLProtocol,默認使用NSURLCache
這些設置項也可以隨時更新:
[self.sCache update:^(STMURLCacheMk *mk) { mk.isDownloadMode(YES); }];預加載名單可以按整個 Web 頁面請求為單位進行:
[self.sCache preLoadByWebViewWithUrls:@[@"https://www.v2ex.com",@"https://www.github.com"];
若需要按單一資源列表預加載,改用 preLoadByRequestWithUrls 這個方法即可。
如果只想快取特定網域或位址,透過白名單來約束範圍,建立時與更新時都可以設置。
NSString *whiteListStr = @"www.starming.com|www.github.com|www.v2ex.com|www.baidu.com"; NSMutableArray *whiteLists = [NSMutableArray arrayWithArray:[whiteListStr componentsSeparatedByString:@"|"]]; self.sCache = [STMURLCache create:^(STMURLCacheMk *mk) { mk.whiteListsHost(whiteLists).whiteUserAgent(@"starming"); }];這裡的 whiteUserAgent 會改寫 webview 的 UserAgent,藉此把 webview 以外的網路請求過濾掉。
建立 STMURLCache 之後,它會把自己設為 NSURLCache 的 URLCache。在 cachedResponseForRequest 方法中取出 NSURLRequest,先比對白名單,再檢查是否有對應快取:有就直接回傳本地的 NSCachedURLResponse,沒有才走網路抓取並寫入快取。STMURLCache 物件釋放時會把 NSURLCache 設為不快取,代表這輪預加載結束;當快取空間超出設定上限,則會整體清空。使用 NSURLProtocol 時的原理基本相同。
建立網域列表設置項 whiteListsHost 與 userAgent 設置項,在建立與更新時寫入。網路請求發起時,透過這些設置項過濾,核心邏輯如下:
//對於域名白名單的過濾 if (self.mk.cModel.whiteListsHost.count > 0) { id isExist = [self.mk.cModel.whiteListsHost objectForKey:[self hostFromRequest:request]]; if (!isExist) { return nil; } } //User-Agent來過濾 if (self.mk.cModel.whiteUserAgent.length > 0) { NSString *uAgent = [request.allHTTPHeaderFields objectForKey:@"User-Agent"]; if (uAgent) { if ![uAgent hasSuffix:self.mk.cModel.whiteUserAgent]) { return nil; } } }快取有兩種實作路徑:一類是 NSURLCache,另一類是 NSURLProtocol。STMURLCache 兩者都支援,透過 STMURLCacheModel 裡的 isUsingURLProtocol 設置項來選擇。
遇到尚未快取的 request 時,會發起請求並把取回的資料以雜湊位址為名寫兩份到本地:一份是資料本體,一份記錄時間與型別,時間用於判定失效。判斷有沒有快取,只需檢查請求位址對應的檔案是否存在。核心程式碼如下:
- (NSCachedURLResponse *)localCacheResponeWithRequest:(NSURLRequest *)request { __block NSCachedURLResponse *cachedResponse = nil; NSString *filePath = [self filePathFromRequest:request isInfo:NO]; NSString *otherInfoPath = [self filePathFromRequest:request isInfo:YES]; NSDate *date = [NSDate date]; NSFileManager *fm = [NSFileManager defaultManager]; if ([fm fileExistsAtPath:filePath]) { //有緩存文件的情況 BOOL expire = false; NSDictionary *otherInfo = [NSDictionary dictionaryWithContentsOfFile:otherInfoPath]; if (self.cacheTime > 0) { NSInteger createTime = [[otherInfo objectForKey:@"time"] integerValue]; if (createTime + self.cacheTime < [date timeIntervalSince1970]) { expire = true; } } if (expire == false) { //從緩存裡讀取數據 NSData *data = [NSData dataWithContentsOfFile:filePath]; NSURLResponse *response = [[NSURLResponse alloc] initWithURL:request.URL MIMEType:[otherInfo objectForKey:@"MIMEType"] expectedContentLength:data.length textEncodingName:[otherInfo objectForKey:@"textEncodingName"]]; NSCachedURLResponse *cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:response data:data]; return cachedResponse; } else { //cache失效了 [fm removeItemAtPath:filePath error:nil]; //清除緩存data [fm removeItemAtPath:otherInfoPath error:nil]; //清除緩存其它信息 return nil; } } else { //從網絡讀取 self.isSavedOnDisk = NO; id isExist = [self.responseDic objectForKey:request.URL.absoluteString]; if (isExist == nil) { [self.responseDic setValue:[NSNumber numberWithBool:TRUE] forKey:request.URL.absoluteString]; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { if (error) { cachedResponse = nil; } else { NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%f", [date timeIntervalSince1970]], @"time", response.MIMEType, @"MIMEType", response.textEncodingName, @"textEncodingName", nil]; BOOL resultO = [dic writeToFile:otherInfoPath atomically:YES]; BOOL result = [data writeToFile:filePath atomically:YES]; if (resultO == NO || result == NO) { } else { } cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:response data:data]; } }]; [task resume]; return cachedResponse; } return nil; } }在設置與更新配置項時,需要建立一個 STMURLCacheModel 單例,把設定同步給 NSURLProtocol 使用。兩者透過 isUsingURLProtocol 設置項區分,而 NSURLProtocol 是以 registerClass 的方式完成註冊。
- (STMURLCache *)configWithMk { self.mk.cModel.isSavedOnDisk = YES; if (self.mk.cModel.isUsingURLProtocol) { STMURLCacheModel *sModel = [STMURLCacheModel shareInstance]; sModel.cacheTime = self.mk.cModel.cacheTime; sModel.diskCapacity = self.mk.cModel.diskCapacity; sModel.diskPath = self.mk.cModel.diskPath; sModel.cacheFolder = self.mk.cModel.cacheFolder; sModel.subDirectory = self.mk.cModel.subDirectory; sModel.whiteUserAgent = self.mk.cModel.whiteUserAgent; sModel.whiteListsHost = self.mk.cModel.whiteListsHost; [NSURLProtocol registerClass:[STMURLProtocol class]]; } else { [NSURLCache setSharedURLCache:self]; } return self; }關閉時兩者的行為也不同,同樣靠設置項分流:
- (void)stop { if (self.mk.cModel.isUsingURLProtocol) { [NSURLProtocol unregisterClass:[STMURLProtocol class]]; } else { NSURLCache *c = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil]; [NSURLCache setSharedURLCache:c]; } [self.mk.cModel checkCapacity]; }白名單處理與快取讀寫的思路與前者類似,差別在資料來源:NSURLCache 方案需要再發一次請求才能拿到資料,而 NSURLProtocol 可以直接在 NSURLConnection 的 Delegate 回呼中取得,省下一次網路往返。這裡有個坑要留意——在 - (void)connection:didReceiveData: 中每次拿到的並不是完整資料,必須在 - (void)connectionDidFinishLoading: 裡把分段資料拼接完整後再落盤。完整實作請參考 STMURLProtocol 的程式碼。
透過 map 攔截網路請求,除了可以做快取,也能用來 mock 介面回應以進行測試。
完整程式碼:STMURLCache(iOS 預加載 Web 頁面方案)