以前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.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");
- }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |