背景
由于苹果对UIWebView的各种放弃,现在向WKWebView上面转才是正道,在从UIWebView转到WKWebView的过程中,还是遇到不少问题的.尤其是WKWebView的拦截资源很成问题.下面介绍下我遇到的问题和做的一些解决办法.
解决方法
1.第一种解决方法
[NSURLProtocol wk_registerScheme:@"http"];
[NSURLProtocol wk_registerScheme:@"https"];
2.第二种解决方法
自定义类遵守WKURLSchemeHandler协议
- (void)webView:(WKWebView *)webView startURLSchemeTask:(id<WKURLSchemeTask>)urlSchemeTask API_AVAILABLE(ios(11.0)){
}
方法选择
方法一
第一种方法还是偷偷的想用UIWebView的方式进行拦截,但是遇到一个致命的问题.POST请求拦截过程中会丢失body体.而且背着苹果偷偷摸摸使用,不敢见光,终究不是好的解决办法.
方法二
本人还是更喜欢方法二,这个第二种毕竟比较光明些.
1.问题一:
但是这个不能拦截到http和https的资源,只能拦截自定义的协议.如果是自己家的服务,自定义协议也挺简单的.
2.问题二:
本以为基本上解决问题了,但是后来又遇到一个问题,在http服务里都很好,但是在https服务里确出现自定义的协议根本不能将请求发送出去的问题,而且现在很多服务明确用https服务,这个问题不好绕过去.后来经过发现
https服务里
[webView evaluateJavaScript:JS_STR completionHandler:^(id _Nullable response, NSError * _Nullable error) {
NSLog(@"js responase = %@",response);
NSLog(@"js error = %@",error.description);
NSString *imgpath = [mainBundle pathForResource:@"www/icon.png" ofType:@""];
NSData *data = [NSData dataWithContentsOfFile:imgpath];
NSURLResponse *responses = [[NSURLResponse alloc] initWithURL:request.URL MIMEType:@"doc" expectedContentLength:data.length textEncodingName:nil];
[urlSchemeTask didReceiveResponse:responses];
[urlSchemeTask didReceiveData:data];
[urlSchemeTask didFinish];
}];
注入CSS代码
/*
* 注入css
*/
-(void)writeCss:(NSString*)css_style webView:(WKWebView*)webView block:(void(^)(id))callBack
{
NSString* css_function = @"function addNewStyle(newStyle) {var styleElement = document.getElementById('styles_js'); if (!styleElement) {styleElement = document.createElement('style');styleElement.type = 'text/css';styleElement.id = 'styles_js';document.getElementsByTagName('head')[0].appendChild(styleElement);}styleElement.appendChild(document.createTextNode(newStyle));console.log('css exc complete');}";
//替换css_style里面的 "和反斜杠
css_style = [css_style stringByReplacingOccurrencesOfString:@"\n" withString:@"\\\\n"];
css_style = [css_style stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
NSString* css_function_z = [NSString stringWithFormat:@"%@; addNewStyle(\"%@\");",css_function,css_style];
[webView evaluateJavaScript:css_function_z completionHandler:^(id _Nullable response, NSError * _Nullable error) {
NSLog(@"responase = %@",response);
NSLog(@"error = %@",error.description);
callBack(response);
}];
}
结论
供需要的人看下,如谁有更好解决办法,也请赐教

2498

被折叠的 条评论
为什么被折叠?



