iOS攔截所有網(wǎng)絡(luò)請(qǐng)求(UIWebView&WKWebView&NSURLConnection&NSURLSession)


面對(duì)流量統(tǒng)計(jì)、請(qǐng)求統(tǒng)一添加header/cookie、離線緩存、dns/代理 等功能,在iOS中可以很好的通過NSURLProtocol來實(shí)現(xiàn),但是在網(wǎng)上很多資料都是不夠全面,WKWebView 沒有實(shí)現(xiàn),因?yàn)閃KWebView 并沒有遵循NSURLProtocol抽象類,本分將完整的攔截 APP所有網(wǎng)絡(luò)請(qǐng)求,并根據(jù)自己需求做功能處理

  • 先介紹一下NSURLProtocol強(qiáng)大功能
    NSURLProtocol 是蘋果提供 URL Loading System 的一個(gè)部分,具體組成如下
    URL Loading System.png

@abstract NSURLProtocol is an abstract class which provides the
basic structure for performing protocol-specific loading of URL
data. Concrete subclasses handle the specifics associated with one
or more protocols or URL schemes.

通過頭文件中,可以清晰的知道NSURLProtocol是一個(gè)抽象類,并且是基礎(chǔ)類,從上圖可以看出只要包含前綴有 NSURLXXX網(wǎng)絡(luò)請(qǐng)求,就會(huì)遵循該抽象類的協(xié)議,所以如果是在用就接口實(shí)現(xiàn)網(wǎng)絡(luò)請(qǐng)求的將無法實(shí)現(xiàn)攔截 即:CFNetwork
框架

  • 自定義NSURLProcotol
  1. 繼承 NSURLProcotol 具體源碼項(xiàng)目 NetworkListener
@interface PMURLProtocol : NSURLProtocol

@end
  1. 向系統(tǒng)注冊(cè)自定義 URLProcotol
+ (void)networkListener:(BOOL)enabled
{
    [PMURLProtocol setEnableListener:enabled];
    
    PMURLSessionConfiguration *sessionConfiguration=[PMURLSessionConfiguration defaultConfiguration];
    
    if (enabled) {
        /** 注冊(cè)自定義 NSURLProcotol */
        [NSURLProtocol registerClass:[PMURLProtocol class]];
        /** 讓 WKWebView 遵循NSURLProcotol */
        [NSURLProtocol wk_registerScheme:@"http"];
        [NSURLProtocol wk_registerScheme:@"https"];
        
        /** NSURLSession 注冊(cè)NSURLProcotol */
        if (![sessionConfiguration isSwizzle]) {
            [sessionConfiguration load];
        }
    }else{
        /** 移除自定義 NSURLProcotol */
        [NSURLProtocol unregisterClass:[PMURLProtocol class]];
        [NSURLProtocol wk_unregisterScheme:@"http"];
        [NSURLProtocol wk_unregisterScheme:@"https"];
        if ([sessionConfiguration isSwizzle]) {
            [sessionConfiguration unload];
        }
    }
}
  • 詢問是否攔截請(qǐng)求
+ (BOOL)canInitWithRequest:(NSURLRequest *)request {
    if (![request.URL.scheme isEqualToString:@"http"] &&
        ![request.URL.scheme isEqualToString:@"https"]) {
        return NO;
    }
    
    /** 防止循環(huán)加載 */
    if ([NSURLProtocol propertyForKey:@"PMURLProtocol" inRequest:request] ) {
        return NO;
    }
    return YES;
}
  • 添加自定義標(biāo)示的request,用于防止循環(huán)加載判斷
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
    
    NSMutableURLRequest *mutableReqeust = [request mutableCopy];
    [NSURLProtocol setProperty:@YES
                        forKey:@"PMURLProtocol"
                     inRequest:mutableReqeust];
    return [mutableReqeust copy];
}
  • 開始request加載
    離線緩存加載可以在這個(gè)地方處理,檢查本地如果存在緩存則直接通過 NSURLProtocolClient 回傳 NSCachedURLResponse相關(guān)信息
- (void)startLoading
{
    NSCachedURLResponse *cachedURLResponse = [PMNetworkCache dataFromRequest:self.request];
    if (cachedURLResponse ) {
        /** 本地存在緩存,直接返回,未發(fā)起網(wǎng)絡(luò)請(qǐng)求 */
        [[self client] URLProtocol:self didReceiveResponse:cachedURLResponse.response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
        [[self client] URLProtocol:self didLoadData:cachedURLResponse.data];
        [[self client] URLProtocolDidFinishLoading:self];
        return;
    }
    
    self.data = [NSMutableData data];
    
    /** 建立網(wǎng)絡(luò)請(qǐng)求 */
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    self.connection = [[NSURLConnection alloc] initWithRequest:[[self class] canonicalRequestForRequest:self.request] delegate:self startImmediately:YES];
#pragma clang diagnostic pop

    /** 創(chuàng)建統(tǒng)計(jì)model */
    self.model = [[PMNetworkHttpModel alloc]initWithRequest:self.request];
}
  • 停止request請(qǐng)求
- (void)stopLoading {
    /** 取消 當(dāng)前NSURLConnection 操作 */
    [self.connection cancel];
    
    if (self.model) {
        self.model.response = (id)self.response;
        self.model.responseData = [self.data copy];
        /** 請(qǐng)求信息保存數(shù)據(jù)庫 */
        [[self.model modelBuilder]saveToDB];
        
        /** 緩存處理 */
        [PMNetworkCache saveCacheWithModel:self.model];
    }
    
    /** 流量統(tǒng)計(jì) */
    CGFloat flow = [PMNetworkCache networkFlowCount] + self.model.responseExpectedContentLength;
    [PMNetworkCache setNetworkFlowCount:flow];
    [[NSNotificationCenter defaultCenter]postNotificationName:URL_PROTOCOL_LOAD_FINISH_NOTIFICATION object:self.model];
}

具體實(shí)現(xiàn)詳看github項(xiàng)目 NetworkListener

實(shí)現(xiàn)效果:


test

test

db
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容