本文主要是介绍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"];}[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类中拦截后替换请求的内容,以下以图片为例
- (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.URLstatusCode: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网络请求的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!