iOS拦截所有网络请求(UIWebView&WKWebView&NSURLConnection&NSURLSession)


面对流量统计、请求统一添加header/cookie、离线缓存、dns/代理 等功能,在iOS中可以很好的通过NSURLProtocol来实现,但是在网上很多资料都是不够全面,WKWebView 没有实现,因为WKWebView 并没有遵循NSURLProtocol抽象类,本分将完整的拦截 APP所有网络请求,并根据自己需求做功能处理

  • 先介绍一下NSURLProtocol强大功能
    NSURLProtocol 是苹果提供 URL Loading System 的一个部分,具体组成如下
    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是一个抽象类,并且是基础类,从上图可以看出只要包含前缀有 NSURLXXX网络请求,就会遵循该抽象类的协议,所以如果是在用就接口实现网络请求的将无法实现拦截 即:CFNetwork
框架

  • 自定义NSURLProcotol
  1. 继承 NSURLProcotol 具体源码项目 NetworkListener
@interface PMURLProtocol : NSURLProtocol

@end
  1. 向系统注册自定义 URLProcotol
+ (void)networkListener:(BOOL)enabled
{
    [PMURLProtocol setEnableListener:enabled];
    
    PMURLSessionConfiguration *sessionConfiguration=[PMURLSessionConfiguration defaultConfiguration];
    
    if (enabled) {
        /** 注册自定义 NSURLProcotol */
        [NSURLProtocol registerClass:[PMURLProtocol class]];
        /** 让 WKWebView 遵循NSURLProcotol */
        [NSURLProtocol wk_registerScheme:@"http"];
        [NSURLProtocol wk_registerScheme:@"https"];
        
        /** NSURLSession 注册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];
        }
    }
}
  • 询问是否拦截请求
+ (BOOL)canInitWithRequest:(NSURLRequest *)request {
    if (![request.URL.scheme isEqualToString:@"http"] &&
        ![request.URL.scheme isEqualToString:@"https"]) {
        return NO;
    }
    
    /** 防止循环加载 */
    if ([NSURLProtocol propertyForKey:@"PMURLProtocol" inRequest:request] ) {
        return NO;
    }
    return YES;
}
  • 添加自定义标示的request,用于防止循环加载判断
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
    
    NSMutableURLRequest *mutableReqeust = [request mutableCopy];
    [NSURLProtocol setProperty:@YES
                        forKey:@"PMURLProtocol"
                     inRequest:mutableReqeust];
    return [mutableReqeust copy];
}
  • 开始request加载
    离线缓存加载可以在这个地方处理,检查本地如果存在缓存则直接通过 NSURLProtocolClient 回传 NSCachedURLResponse相关信息
- (void)startLoading
{
    NSCachedURLResponse *cachedURLResponse = [PMNetworkCache dataFromRequest:self.request];
    if (cachedURLResponse ) {
        /** 本地存在缓存,直接返回,未发起网络请求 */
        [[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];
    
    /** 建立网络请求 */
#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

    /** 创建统计model */
    self.model = [[PMNetworkHttpModel alloc]initWithRequest:self.request];
}
  • 停止request请求
- (void)stopLoading {
    /** 取消 当前NSURLConnection 操作 */
    [self.connection cancel];
    
    if (self.model) {
        self.model.response = (id)self.response;
        self.model.responseData = [self.data copy];
        /** 请求信息保存数据库 */
        [[self.model modelBuilder]saveToDB];
        
        /** 缓存处理 */
        [PMNetworkCache saveCacheWithModel:self.model];
    }
    
    /** 流量统计 */
    CGFloat flow = [PMNetworkCache networkFlowCount] + self.model.responseExpectedContentLength;
    [PMNetworkCache setNetworkFlowCount:flow];
    [[NSNotificationCenter defaultCenter]postNotificationName:URL_PROTOCOL_LOAD_FINISH_NOTIFICATION object:self.model];
}

具体实现详看github项目 NetworkListener

实现效果:


test

test

db
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。