IOS JavaScriptCore介绍

本文主要转自:https://www.jianshu.com/p/cdaf9bc3d65d

                     http://blog.csdn.net/u011993697/article/details/51577295

oc与JS的交互实现方式有很多,在ios7之前用的比较多的是WebViewJavaScriptBridge,在ios7之后苹果将JavaScriptCore框架开放,这样就增加一种选择。

1、准备工作

首先要导入JavaScriptCore的头文件

#import <JavaScriptCore/JavaScriptCore.h>

2、用webview加载HTML文件,这里用的是本地html

- (void)viewDidLoad
{
[super viewDidLoad];

NSString *path = [[[NSBundle mainBundle] bundlePath]  stringByAppendingPathComponent:@"JSCallOC.html"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]];
[self.webView loadRequest:request];
}

3、在进行JS交互之前,需要通过JSContent创建一个使用JS的环境

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    // Undocumented access to UIWebView's JSContext
    self.context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    
    // 打印异常
    self.context.exceptionHandler =
    ^(JSContext *context, JSValue *exceptionValue)
    {
        context.exception = exceptionValue;
        NSLog(@"%@", exceptionValue);
    };
    
   
    
}

4、JS调用OC代码

4.1、通过block调用

<input type="button" value="测试log" onclick="log('测试');" />
self.context[@"log"] = ^(NSString *str)
{
NSLog(@"%@", str);
};

4.2、实现JSExport协议

定义需要暴露给JS的内容

<input type="button" value="计算阶乘" onclick="native.calculateForJS(input.value);" />
@protocol TestJSExport <JSExport>

JSExportAs
(calculateForJS ,
 - (void)handleFactorialCalculateWithNumber:(NSNumber *)number
 );

@end
 // 以 JSExport 协议关联 native 的方法
self.content[@"native"] = self;

5、OC调用JS代码

在OC中,所有表示JS中对象,都用JSValue来创建,通过objectForKeyedSubscript方法或者直接使用下标的方法获取JS对象,然后使用callWithArguments方法来执行函数。

// 方法一.  
 JSValue *function = [self.context objectForKeyedSubscript:@"factorial"];
// 方法二.
JSValue * function = self.context[@"factorial"];

JSValue *result = [function callWithArguments:@[inputNumber]];
self.showLable.text = [NSString stringWithFormat:@"%@", [result toNumber]];

一个demon连接:https://github.com/shaojiankui/JavaScriptCore-Demo

6、封装

将javascriptcore进行封装,更方便ios 和 前端进行数据的交互和方法的调用,使用方式和webviewjavascriptbridge一样,先在plist文件配置,对外暴露的oc接口需要实现指定的协议。 
demo:https://github.com/HZQuan/WebViewJavaScriptCoreBridge

posted @ 2018-02-23 13:40  燃烧吧,少年  阅读(523)  评论(0编辑  收藏  举报