利用JavaScriptCore实现OC和JS交互

JavaScriptCore

JavaScriptCore是webkit的一个重要组成部分,主要是对JS进行解析和提供执行环境。iOS7后苹果在iPhone平台推出,极大的方便了我们对js的操作。

首先创建webView,读取本地的html文件
 NSURL* htmlURL = [[NSBundle mainBundle] URLForResource: @"demo" withExtension: @"html"];
[_webView loadRequest: [NSURLRequest requestWithURL: htmlURL]];

在demo中,我们要实现4种情况

  • JS调用OC
  • JS调用OC并传递参数
  • OC调用JS
  • OC调用JS并传递参数

html文件中代码如下

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript">
    function showAlert(){
        alert('OC call JS with no argument');
    }
    function showAlertWithString(string){
        alert(string);
    }
    function callOCWithArgument() {
        jsCallOCWithArgument('参数1 ','参数2 ','参数3');
    }
    </script>
</head>
<body>
    </br>
    </br>
    </br>
    </br>
    <form>
        <button type='button' onclick='callOC()'>jsCallOC</button>
        <button type='button' onclick='callOCWithArgument()'>jsCallOCWithArgument</button>
    </form>
</body>
</html>
JS调用OC

在webView的代理方法webViewDidFinishLoad中

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    
    _context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    __weak typeof(self) weakSelf = self;
    _context.exceptionHandler = ^(JSContext *context, JSValue *exception) {
        weakSelf.context.exception = exception;
    };
    
    //js调用OC
    _context[@"callOC"] = ^() {
        NSArray *args = [JSContext currentArguments];
        for (JSValue *jsVal in args) {
            NSLog(@"%@", jsVal.toString);
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"arguments" message:@"JS Call OC With No Argument" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction * action = [UIAlertAction actionWithTitle:@"Done" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alertView addAction:action];
            [weakSelf presentViewController:alertView animated:YES completion:nil];
        });
    };
    
    _context[@"jsCallOCWithArgument"] = ^() {
        NSArray *args = [JSContext currentArguments];
        NSMutableString * stirng = [NSMutableString string];
        for (JSValue * value in args) {
            [stirng appendString:value.toString];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"arguments" message:stirng preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction * action = [UIAlertAction actionWithTitle:@"Done" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            }];
            [alertView addAction:action];
            [weakSelf presentViewController:alertView animated:YES completion:nil];
        });
    };   
}

我们定义一个block,然后保存到context里面,其实就是转换成了JS中命名为callOC的function。然后我们直接执行这个function,调用的就是我们的block里面的内容了。
传过来的参数可以通过[JSContext currentArguments]这个array接受,里面是JSValue对象。

OC调用JS

初始化两个Button,在点击事件中实现如下方法

- (IBAction)callJS:(id)sender {
    [_context evaluateScript:@"showAlert()"];
}
- (IBAction)callJSWithArguments:(id)sender {
    
    [_context evaluateScript:@"showAlertWithString('OC call JS with arguments')"];
//    [_context[@"showAlertWithString"] callWithArguments:@[@"OC call JS with arguments"]];
}

即可实现OC调用JS。

demo已上传到github,需要的可以看一下。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 随着H5技术的兴起,在iOS开发过程中,难免会遇到原生应用需要和H5页面交互的问题。其中会涉及方法调用及参数传值等...
    Chris_js阅读 3,163评论 1 8
  • 前言 Web 页面中的 JS 与 iOS Native 如何交互是每个 iOS 猿必须掌握的技能。而说到 Nati...
    幽城88阅读 2,264评论 1 8
  • 前言### 最近公司项目进行比较激烈,没有时间写demo,但是时间就像是海绵里的水,挤挤总是会有的。在公司的项目中...
    摸着石头过河_崖边树阅读 2,314评论 2 14
  • 写在前面 本篇文章是对我一次组内分享的整理,大部分图片都是直接从keynote上截图下来的,本来有很多炫酷动效的,...
    等开会阅读 14,569评论 6 69
  • 本文由我们团队的 纠结伦 童鞋撰写。 写在前面 本篇文章是对我一次组内分享的整理,大部分图片都是直接从keynot...
    知识小集阅读 15,313评论 11 172