美文网首页iOS视图
项目中的WKWebView替换UIWebView

项目中的WKWebView替换UIWebView

作者: iOS_zy | 来源:发表于2022-05-09 06:40 被阅读0次

    最近帮朋友接手个老项目加一点小需求,需求加完了发现webview有些显示上面小问题,就请我帮忙再排查下,这一排查不要紧,搜索UIWebview关键字,竟然发现整个项目中含有83处,包含文件29个,当时心就一凉。下面是我通宵翻找WKWebView替换UIWebView的文章摘要部分,网上文章太多,东一篇西一篇的,不好借鉴,总结一下,方便同学们随来随取,下面上代码:

    一:基本使用

    首先说下基本用法:

    • UIWebView:
    UIWebView *webView = [[UIWebView alloc] init];
    NSURL *url = [NSURL URLWithString:@"https://www.hujiang.com"];
    [webView loadRequest:[NSURLRequest requestWithURL:url]];
    
    • WKWebView:
    #import <WebKit/WebKit.h>
    WKUserContentController *wkUController = [[WKUserContentController alloc] init];
    WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
    wkWebConfig.userContentController = wkUController;
            
    WKWebView* mainWebView = [[WKWebView alloc] initWithFrame:self.view.frameconfiguration:wkWebConfig];
    mainWebView.navigationDelegate = self;
    mainWebView.backgroundColor = [UIColor clearColor];
    

    二:替换

    1、scalesPageToFit 属性替换:

    在WKWebView中不支持scalesPageToFit属性,可以通过注入js的方法实现:

    //以下代码适配文本大小,由UIWebView换为WKWebView后,会发现字体小了很多,这应该是WKWebView与html的兼容问题,解决办法是修改原网页,要么我们手动注入JS
    NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta); var imgs = document.getElementsByTagName('img');for (var i in imgs){imgs[i].style.maxWidth='100%';imgs[i].style.height='auto';}";
    WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
            
    WKUserContentController *wkUController = [[WKUserContentController alloc] init];
    [wkUController addUserScript:wkUScript];
    
    2、UIWebView 和WKWebView对应代理方法

    @protocol WKNavigationDelegate; //类似于UIWebView的加载成功、失败、是否允许跳转等 @protocol WKUIDelegate; //主要是一些alert、打开新窗口之类的

    2.1、shouldStartLoadWithRequest
    • UIWebView
    -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
        return YES;
    }
    
    • WKWebView
    //先:针对一次action来决定是否允许跳转,action中可以获取request
    - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
        //允许与否都需要调用decisionHandler,如:
        decisionHandler(WKNavigationActionPolicyAllow);
    }
    //后:根据response来决定,是否允许跳转
    - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
        //允许与否都需要调用decisionHandler,如:
        decisionHandler(WKNavigationActionPolicyCancle);
    }
    
    2.2、开始加载
    • UIWebView
    - (void)webViewDidStartLoad:(UIWebView *)webView;
    
    • WKWebView
    - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation;
    
    2.3、加载成功
    • UIWebView:
    - (void)webViewDidFinishLoad:(UIWebView *)webView;
    
    • WKWebView:
    - (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation;
    
    2.4、加载失败
    • UIWebView:
    - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;
    
    • WKWebView:
    - (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error;
    
    3、Native和JS互相调用:
    3.1、Native调用js
    • UIWebView:
    [weiview stringByEvaluatingJavaScriptFromString:jsString];
    
    • WKWebView:
    [wkWebView evaluateJavaScript:@"jsFunction"
                completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        NSString *title = response;
    }];
    
    3.2、js调用Native
    • UIWebView:
    //第一种方法,简单
    - (nullable NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;
    
    
    //第二种:通过拦截URL的方式:
    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
        NSURL *URL = request.URL;    
        if ([URL.scheme isEqualToString:@"urlscheme"]) {
            if ([URL.host isEqualToString:@"jsFunction"]) {
                NSLog(@"拦截执行js中的方法: %@", URL.query);
                return NO;
            }
        }
        return YES;
    }
    
    • WKWebView:
      第一种方式:
    WKUserContentController *userContent = [[WKUserContentController alloc] init];
    [userContent addScriptMessageHandler:id<WKScriptMessageHandler> name:@"jsFunction"];
        
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.userContentController = userContent;
    WKWebView *wkWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
    

    在代理方法中截取:

    -  (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
        if ([message.name isEqualToString:@"jsFunction"]) {
            NSLog(@"native执行js的方法:%@",message.body);
        }
    }
    
    //注意在合适的地方移除messageHandler:
    - (void)dealloc {
        [wkWebView.configuration.userContentController removeScriptMessageHandlerForName:@"jsFunction"];
    }
    

    第二种方式:URL拦截
    缺点:无法直接获取本次交互的返回值,比较适合单向传参,且不关心回调的情景,比如h5页面跳转到native页面等

    - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
        //可以通过navigationAction.navigationType获取跳转类型,如新链接、后退等
        NSURL *URL = navigationAction.request.URL;
        //判断URL是否符合自定义的URL Scheme
        if ([URL.scheme isEqualToString:@"urlscheme"]) {
            //根据不同的业务,来执行对应的操作,且获取参数
            if ([URL.host isEqualToString:@"jsFunction"]) {
                decisionHandler(WKNavigationActionPolicyCancel);
                return;
            }
        }
        decisionHandler(WKNavigationActionPolicyAllow);
    }
    
    下面你可能会用得到的文章:

    里面有左滑返回上一步的详细代码
    iOS WKWebView的使用
    UIWebView 改 WKWebView解决各种问题
    WKWebView 使用及注意事项
    WKWebView使用过程中遇到的坑
    iOS-WKWebView设置 Cookie
    WKWebView的cookie探究

    相关文章

      网友评论

        本文标题:项目中的WKWebView替换UIWebView

        本文链接:https://www.haomeiwen.com/subject/jiwcurtx.html