iOS:js与OC交互总结(二)

二. WKWebView篇


先贴上使用的部分html代码

<body>
    <!-- <input type="button" value="按钮" onclick="javascrtpt:window.location.href='https://www.baidu.com'"> -->
    <button id="btn" onclick="btnClick()">百度</button> 
    <button id="btn" onclick="btnActionNoParams()">WK不带参数</button> 
    <button id="btn" onclick="btnActionWithParams()">WK带参数</button> 
    <button id="jscontextbtn" onclick="jscontextmethod('参数1')">JSContext按钮</button>   
    <script>
        function btnClick() {
            window.location.href = 'jsCallOC://www.baidu.com'
        }
        function btnActionNoParams() {
            window.webkit.messageHandlers.jscalloc1.postMessage(null)
        }
        function btnActionWithParams() {
            window.webkit.messageHandlers.jscalloc2.postMessage({title:'标题',content:'内容',url:'https://www.baidu.com'})
        }
        function jsTest() {
            //alert('这是一个js方法')
            console.log('这是一个js方法');
        }
        function jsTestWithParams(param1) {
            //alert(param1);
            console.log(param1);
        }
        
    </script>
</body>

引入WKWebView头文件,添加协议:

#import <WebKit/WebKit.h>
@interface WKViewController ()<WKNavigationDelegate,WKScriptMessageHandler,WKUIDelegate>

WKNavigationDelegate:使用拦截url方式与js交互时用到;
WKScriptMessageHandler:使用MessageHandler方式与js交互时用到;
WKUIDelegate:与js有UI上交互时用到;
具体要添加哪种协议,视情况而定。

1. 拦截url方式

创建WKWebView实例对象,设置协议

self.myWebView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 88, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-88)];
    NSURL *url = [[NSBundle mainBundle]URLForResource:@"test.html" withExtension:nil];
    [self.myWebView loadRequest:[NSURLRequest requestWithURL:url]];
    self.myWebView.navigationDelegate = self;
    [self.view addSubview:self.myWebView];
1.1 js调用OC

navigationDelegate协议方法中(与UIWebView协议拦截url相似)

-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    
    NSURL *url = navigationAction.request.URL;  //jscalloc://www.baidu.com
    NSString *scheme = [url scheme];  //jscalloc
//    NSString *host = [url host];  //www.baidu.com
//    NSString *policy = [url query];
    if ([scheme isEqualToString:@"jscalloc"]) {
        
        /*
        在这里执行OC代码操作
        ......
         */
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"js调用oc" message:@"点击js方法,调用此oc方法(这是个OC弹框)" preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleCancel handler:nil]];
        [self presentViewController:alertVC animated:YES completion:nil];
        
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    
    decisionHandler(WKNavigationActionPolicyAllow);
}

注意:
1.如果实现了这个代理方法,就必须得调用decisionHandler这个 block,否则会导致 app 奔溃。block 参数是一个枚举值,WKNavigationActionPolicyCancel代表取消加载,相当于UIWebView的代理方法return NO的情况;
WKNavigationActionPolicyAllow代表允许加载,相当于UIWebView的代理方法中 return YES的情况。

1.2 oc调用js

jsTestWithParams为js中方法,带一个参数

function jsTestWithParams(param1) {
            console.log(param1)
        }

在OC中如此调用

-(void)ocCallJS:(UIButton *)btn{
    NSString *string = [NSString stringWithFormat:@"jsTestWithParams('%@')",@"这是个js方法哈哈哈"];
    //NSString *string = [NSString stringWithFormat:@"jsTest()"];
    [self.myWebView evaluateJavaScript:string completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSLog(@"result:%@\nerror:%@",result,error);
    }];
}

可以在浏览器控制台看到此方法打印结果:


ocCallJS.png
2. 使用messageHandlers,利用WKWebView的新特性MessageHandler来实现JS调用原生方法

2.1 js调用oc

这里有两个类:
WKWebViewConfiguration:WKWebView配置信息
WKUserContentController:提供js与oc交互方法

通过addScriptMessageHandler方法注册js调用oc方法,因为addScriptMessageHandler会有循坏引用的问题,造成内存泄漏,所以在页面消失时,需移除。

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.myWebView.configuration.userContentController addScriptMessageHandler:self name:@"jscalloc1"];
    [self.myWebView.configuration.userContentController addScriptMessageHandler:self name:@"jscalloc2"];

}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.myWebView.configuration.userContentController removeScriptMessageHandlerForName:@"jscalloc1"];
    [self.myWebView.configuration.userContentController removeScriptMessageHandlerForName:@"jscalloc2"];
}

jscalloc1jscalloc2在上面html代码查看具体的使用

WKScriptMessageHandler代理方法中:

-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    NSString *str = message.name;
    if ([str isEqualToString:@"jscalloc1"]) {
        [self jsCallOC];
    }else if([str isEqualToString:@"jscalloc2"]){
        //获取传过来的参数
        //{title:'标题',content:'内容',url:'https://www.baidu.com'}
        NSDictionary *dic = message.body;
        NSLog(@"dic==%@",dic);
    }
}
-(void)jsCallOC{
    NSLog(@"js调用oc");
}
2.2 oc调用js

与上述oc调用js是一样的方法

-(void)ocCallJS:(UIButton *)btn{
    NSString *string = [NSString stringWithFormat:@"jsTestWithParams('%@')",@"这是个js方法哈哈哈"];
    //NSString *string = [NSString stringWithFormat:@"jsTest()"];
    [self.myWebView evaluateJavaScript:string completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSLog(@"result:%@\nerror:%@",result,error);
    }];
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容