iOS 通过NSURLProtocol拦截WKWebView网络请求
以前NSURLProtocol可以直接拦截UIWebView,后面升级成WKWebView发现拦截不到了有细心爱研究的老铁发现了 [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"];
}
]; 2.在你自界说的NSURLProtocol类中实现拦截
+ (BOOL)canInitWithRequest:(NSURLRequest *)request{
NSString *abstring = request.URL.absoluteString;
if () {
return YES;
}
return NO;
}
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request
{
return request;
} 3.在你自界说的NSURLProtocol类中拦截后更换请求的内容,以下以图片为例
- (void)startLoading{
NSString *urlPathString = super.request.URL.absoluteString;
if () {
urlPathString = ;
}
NSData *imageData = ];
NSMutableDictionary *header = ;
header[@"Content-Length"] = ;
NSHTTPURLResponse *response = [ initWithURL:self.request.URL
statusCode:200 HTTPVersion:@"1.1" headerFields:header];
//回调
;
;
;
}
- (void)stopLoading{
NSLog(@"stop");
}
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页:
[1]