JSCore的基本使用
xiaolin
9年前
<h2><strong>一、简单介绍</strong></h2> <p>JSCore全称为 JavaScriptCore ,是苹果公司在iOS中加入的一个新的framework。该framework为OC与JS代码相互操作的提供了极大的便利。该工程默认是没有导入工程中的,需要我们手动添加。</p> <p style="text-align: center;"><img src="https://simg.open-open.com/show/fd9043592defa18a49bc0b79cd2a5e6b.png"></p> <p>添加完成后,我们可以看到JavaScriptCore.h中包含以下5个主要的文件。</p> <pre> <code class="language-objectivec">#import "JSContext.h" #import "JSValue.h" #import "JSManagedValue.h" #import "JSVirtualMachine.h" #import "JSExport.h"</code></pre> <p>JSContext: 代表JavaScript的执行环境。你可以创建JSContent在OC环境中执行JavaScript脚本,同时也可以在JavaScript脚本中访问OC中的值或者方法。</p> <p>JSValue:是OC和JavaScript值相互转化的桥梁。他提供了很多方法把OC和JavaScript的数据类型进行相互转化。其一一对应关系如下表所示:</p> <p><img src="https://simg.open-open.com/show/2d510d075b6db92870a4af78179ce08e.png"></p> <p>JSManagedValue:JSValue的包装类。JS和OC对象的内存管理辅助对象。由于JS内存管理是垃圾回收,并且JS中的对象都是强引用,而OC是引用计数。如果双方相互引用,势必会造成循环引用,而导致内存泄露。我们可以用JSManagedValue保存JSValue来避免。</p> <p>JSVirtualMachine: JS运行的虚拟机。可以支持并行的JavaScript执行,管理JavaScript和OC转换中的内存管理。</p> <p>JSExport:一个协议,如果JS对象想直接调用OC对象里面的方法和属性,那么这个OC对象只要实现这个JSExport协议就可以了。</p> <p>下面我们通过实例案例来学习JSCore的用法。</p> <h2><strong>二、OC中调用JS方法</strong></h2> <p>案例一:我在js中定义了一个函数add(a,b),我们需要在OC中进行调用。</p> <pre> <code class="language-objectivec">-(void)OCCallJS{ self.context = [[JSContext alloc] init]; NSString *js = @"function add(a,b) {return a+b}"; [self.context evaluateScript:js]; JSValue *addJS = self.context[@"add"]; JSValue *sum = [addJS callWithArguments:@[@(10),@(17)]]; NSInteger intSum = [sum toInt32]; NSLog(@"intSum: %zi",intSum); }</code></pre> <h2><strong>三、JS中调用OC方法</strong></h2> <p>JS中调用OC有两种方法,第一种为block调用,第二种为JSExport protocol。</p> <p>案例二:我们在OC中定义了一个如下方法,我们需要在JS中对它进行调用</p> <pre> <code class="language-objectivec">-(NSInteger)add:(NSInteger)a and:(NSInteger)b{ return a+b; }</code></pre> <h3><strong>3.1、block调用</strong></h3> <pre> <code class="language-objectivec">-(void)JSCallOC_block{ self.context = [[JSContext alloc] init]; __weak typeof(self) weakSelf = self; self.context[@"add"] = ^NSInteger(NSInteger a, NSInteger b){ return [weakSelf add:a and:b]; }; JSValue *sum = [self.context evaluateScript:@"add(4,5)"]; NSInteger intSum = [sum toInt32]; NSLog(@"intSum: %zi",intSum); }</code></pre> <h3><strong>3.2、JSExport protocol</strong></h3> <p>第一步:定义一个遵守JSExport的AddJSExport协议。</p> <pre> <code class="language-objectivec">@protocol AddJSExport //用宏转换下,将JS函数名字指定为add; JSExportAs(add, - (NSInteger)add:(NSInteger)a and:(NSInteger)b); @property (nonatomic, assign) NSInteger sum; @end </code></pre> <p>第二步:新建一个对象AddJSExportObj,去实现以上协议。</p> <pre> <code class="language-objectivec">AddJSExportObj.h @interface AddJSExportObj : NSObject @property (nonatomic, assign) NSInteger sum; @end AddJSExportObj.m @implementation AddJSExportObj -(NSInteger)add:(NSInteger)a and:(NSInteger)b{ return a+b; } @end </code></pre> <p>第三步:在VC中进行JS调用</p> <pre> <code class="language-objectivec">-(void)JSCallOC_JSExport{ self.context = [[JSContext alloc] init]; //异常处理 self.context.exceptionHandler = ^(JSContext *context, JSValue *exception){ [JSContext currentContext].exception = exception; NSLog(@"exception:%@",exception); }; self.addObj = [[AddJSExportObj alloc] init]; self.context[@"OCAddObj"] = self.addObj;//js中的OCAddObj对象==>OC中的AddJSExportObj对象 [self.context evaluateScript:@"OCAddObj.sum = OCAddObj.add(2,30)"]; NSLog(@"%zi",self.addObj.sum); }</code></pre> <h2><strong>四、一个从服务端下发JS脚本,执行本地方法的实现思路</strong></h2> <p>案例三:本地定义了一系列方法,可以通过服务端下发js脚本去控制具体去执行那些方法。这样就可以在远端实现对于客户端的控制。</p> <p>第一步:预置本地方法</p> <pre> <code class="language-objectivec">-(void)initJS{ __weak typeof(self) weakSelf = self; self.context[@"execute1"] = ^(){ [weakSelf execute1]; }; self.context[@"execute2"] = ^(){ [weakSelf execute2]; }; } -(void)execute1{ NSLog(@"execute1"); } -(void)execute2{ NSLog(@"execute2"); }</code></pre> <p>第二步:服务端下发脚本</p> <pre> <code class="language-objectivec">-(NSString *)getJS{ //可以从服务端下发 //return @"execute1()"; return @"execute2()"; }</code></pre> <p>第三步:根据服务端下发脚本执行</p> <pre> <code class="language-objectivec">-(void)executeByJs{ [self initJS]; NSString *js = [self getJS]; [self.context evaluateScript:js]; }</code></pre> <h2><strong>五、JSCore在Web容器中的使用</strong></h2> <p>在UIWebView中,我们可以在 - (void)webViewDidFinishLoad:(UIWebView *)webView 方法中,通过KVC的方式获取到当前容器的JSContent对象,通过该对象,我们就可以方便的进行hybrid操作。</p> <pre> <code class="language-objectivec">JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];</code></pre> <p>案例演示:在html中调研OC代码中的分享功能和调用相机功能。</p> <p>第一步:HelloWord.html代码如下:</p> <pre> <code class="language-objectivec">function jsCallNative(){ WBBridge.callCamera(); } function jsCallNative2(){ var shareInfo = "分享内容"; var str = WBBridge.share(shareInfo); alert(str); } </code></pre> <p>第二步:实现一个遵守JSExport的协议WebViewJSExport</p> <pre> <code class="language-objectivec">@protocol WebViewJSExport - (void)callCamera; - (NSString*)share:(NSString*)shareString; @end </code></pre> <p>第三步:当前VC需要实现WebViewJSExport</p> <pre> <code class="language-objectivec">@interface ViewController () @property (nonatomic, strong) JSContext *context; @property (nonatomic, strong) UIWebView *webView; @end @implementation ViewController -(void)initWebView{ self.context = [[JSContext alloc] init]; _webView = [[UIWebView alloc] initWithFrame:self.view.bounds]; _webView.delegate = self; [self.view addSubview:_webView]; NSURL *url = [[NSURL alloc] initWithString:@"http://localhost:8080/myDiary/HelloWorld.html"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [self.webView loadRequest:request]; } - (void)webViewDidFinishLoad:(UIWebView *)webView{ JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; _context = context; // 将本对象与 JS 中的 WBBridge 对象桥接在一起,在 JS 中 WBBridge 代表本对象 [_context setObject:self forKeyedSubscript:@"WBBridge"]; _context.exceptionHandler = ^(JSContext* context, JSValue* exceptionValue) { context.exception = exceptionValue; NSLog(@"异常信息:%@", exceptionValue); }; } - (void)callCamera{ NSLog(@"调用相机"); } - (NSString*)share:(NSString*)shareString{ NSLog(@"分享::::%@",shareString); return @"分享成功"; } @end </code></pre> <p>这样我们就可以在webView中调用我们native组建了,实现了一个简单的hybird功能。这就补充了在UIWebView实现hybird功能的方式。</p> <p>补充</p> <p>对于WKWebView,目前还没有能够拿到JSContent的对象的方式。</p> <h2><strong>六、参考资料</strong></h2> <p><a href="/misc/goto?guid=4959725531340762340" rel="nofollow,noindex">javascriptcore官方资料</a></p> <p><a href="/misc/goto?guid=4959725531437596393" rel="nofollow,noindex">JavaScriptCore 使用</a></p> <p><a href="/misc/goto?guid=4959725531517068205" rel="nofollow,noindex">iOS7新JavaScriptCore框架入门介绍</a></p> <p> </p> <p>来自:http://www.cocoachina.com/ios/20161117/18117.html</p> <p> </p>