美文网首页
iOS-JS调用OC代码

iOS-JS调用OC代码

作者: SmileYang966 | 来源:发表于2020-05-12 09:37 被阅读0次

设计思路

  1. 创建WKWebViewConfiguration对象,配置该对象的userContentController属性,这里需要注册html中预留的接口“jsCallOC”
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init];
    
    //2.配置JS
    WKUserContentController *userContentController = [[WKUserContentController alloc]init];
    //定义了js中将要调用oc的方法名
    //注册html中预留的接口jsCallOC
    [userContentController addScriptMessageHandler:self name:@"jsCallOC"];
    config.userContentController = userContentController;
  1. 创建wkwebView对象
    //3.显示wkWebView
    self.webView = [[WKWebView alloc]initWithFrame:CGRectMake(10,100,200,400) configuration:config];
    self.webView.UIDelegate = self;
    [self.view addSubview:self.webView];
    
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"html"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
  1. 准备HTML代码,创建一个button,点击button之后会调用
    window.webkit.messageHandlers.jsCallOC.postMessage(dict)方法,该方法会将字典数据传递给oc代码层。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>This is a testing</title>
</head>
<body>
        <h1>Tested Html</h1>
        <button name="Click Me" type="button" onclick="onClickButton()" style="width: 100px; height: 30px;"></button>
        
        <script type="application/javascript">

            function onClickButton() {
                var list = [1,2,3];
                var dict = {"name" : "阳君","qq":"3300333221","data":"123","array":list};
                alert(dict);
                window.webkit.messageHandlers.jsCallOC.postMessage(dict);
            }

        </script>
</body>
</html>
  1. OC代码层会响应js的事件传递,并调用userContentController: didReceiveScriptMessage方法。这里可以做相应的操作。
//这里取得oc的方法名
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    NSLog(@"方法名:%@",message.name);
    NSLog(@"参数名:%@",message.body);
    
    //方法名
    NSString *methods = [NSString stringWithFormat:@"%@:",message.name];
    SEL selector = NSSelectorFromString(methods);
    
    //调用方法
    if ([self respondsToSelector:selector]) {
        [self performSelector:selector withObject:message.body];
    }else{
        NSLog(@"未实行方法:%@",methods);
    }
}

-(void)jsCallOC:(id)body{
    NSLog(@"jsCallOC function called");
}

相关文章

网友评论

      本文标题:iOS-JS调用OC代码

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