iOS 通过NSURLProtocol拦截WKWebView网络请求

05-01 阅读 0评论

以前NSURLProtocol可以直接拦截UIWebView,后面升级成WKWebView发现拦截不到了

iOS 通过NSURLProtocol拦截WKWebView网络请求,iOS 通过NSURLProtocol拦截WKWebView网络请求,词库加载错误:未能找到文件“C:\Users\Administrator\Desktop\火车头9.8破解版\Configuration\Dict_Stopwords.txt”。,注册,URL,步骤,第1张
(图片来源网络,侵删)

有细心爱研究的老铁发现了 [WKBrowsingContextController  registerSchemeForCustomProtocol:]  这个函数的存在

所以还是可以拦截的

直接上步骤

1.在控制器或者你喜欢的地方注册NSURLProtocol(调用以下代码)

    Class cls = NSClassFromString(@"WKBrowsingContextController");
    SEL sel = NSSelectorFromString(@"registerSchemeForCustomProtocol:");
    if ([(id)cls respondsToSelector:sel]) {
        [(id)cls performSelector:sel withObject:@"http"];
        [(id)cls performSelector:sel withObject:@"https"];
    }
    [NSURLProtocol registerClass:[CustomProtocol class]];

2.在你自定义的NSURLProtocol类中实现拦截

+ (BOOL)canInitWithRequest:(NSURLRequest *)request{
    
    NSString *abstring = request.URL.absoluteString;
    
    if ([abstring containsString:@"你喜欢的标记"]) {
        return YES;
    }
    
    return NO;
}
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request
{
    return request;
}

3.在你自定义的NSURLProtocol类中拦截后替换请求的内容,以下以图片为例

iOS 通过NSURLProtocol拦截WKWebView网络请求,iOS 通过NSURLProtocol拦截WKWebView网络请求,词库加载错误:未能找到文件“C:\Users\Administrator\Desktop\火车头9.8破解版\Configuration\Dict_Stopwords.txt”。,注册,URL,步骤,第2张
(图片来源网络,侵删)
- (void)startLoading{
    
    NSString *urlPathString = super.request.URL.absoluteString;
    
    if ([urlPathString containsString:@"你喜欢的标记"]) {
        
        urlPathString = [urlPathString stringByReplacingOccurrencesOfString:@"你喜欢的标记" withString:@"你喜欢的标记2"];
    }
    
    
    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlPathString]];
    
    NSMutableDictionary *header = [NSMutableDictionary dictionary];
    header[@"Content-Length"] = [NSString stringWithFormat:@"%ld",imageData.length];
    
    NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.request.URL
               statusCode:200 HTTPVersion:@"1.1" headerFields:header];
    //回调
    [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed];
    [self.client URLProtocol:self didLoadData:imageData];
    [self.client URLProtocolDidFinishLoading:self];
}
- (void)stopLoading{
    NSLog(@"stop");
}
iOS 通过NSURLProtocol拦截WKWebView网络请求,iOS 通过NSURLProtocol拦截WKWebView网络请求,词库加载错误:未能找到文件“C:\Users\Administrator\Desktop\火车头9.8破解版\Configuration\Dict_Stopwords.txt”。,注册,URL,步骤,第3张
(图片来源网络,侵删)

免责声明
本网站所收集的部分公开资料来源于AI生成和互联网,转载的目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。
文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

发表评论

快捷回复: 表情:
评论列表 (暂无评论,人围观)

还没有评论,来说两句吧...

目录[+]