JSCore的基本使用====

来源:互联网 发布:河南极速网络 编辑:程序博客网 时间:2024/06/05 02:43

一、简单介绍


JSCore全称为JavaScriptCore,是苹果公司在iOS中加入的一个新的framework。该framework为OC与JS代码相互操作的提供了极大的便利。该工程默认是没有导入工程中的,需要我们手动添加。




添加完成后,我们可以看到JavaScriptCore.h中包含以下5个主要的文件。


#import "JSContext.h"#import "JSValue.h"#import "JSManagedValue.h"#import "JSVirtualMachine.h"#import "JSExport.h"


JSContext: 代表JavaScript的执行环境。你可以创建JSContent在OC环境中执行JavaScript脚本,同时也可以在JavaScript脚本中访问OC中的值或者方法。


JSValue:是OC和JavaScript值相互转化的桥梁。他提供了很多方法把OC和JavaScript的数据类型进行相互转化。其一一对应关系如下表所示:



JSManagedValue:JSValue的包装类。JS和OC对象的内存管理辅助对象。由于JS内存管理是垃圾回收,并且JS中的对象都是强引用,而OC是引用计数。


如果双方相互引用,势必会造成循环引用,而导致内存泄露。我们可以用JSManagedValue保存JSValue来避免。


JSVirtualMachine: JS运行的虚拟机。可以支持并行的JavaScript执行,管理JavaScript和OC转换中的内存管理。


JSExport:一个协议,如果JS对象想直接调用OC对象里面的方法和属性,那么这个OC对象只要实现这个JSExport协议就可以了。


下面我们通过实例案例来学习JSCore的用法。


二、OC中调用JS方法


案例一:我在js中定义了一个函数add(a,b),我们需要在OC中进行调用。


-(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);}


三、JS中调用OC方法


JS中调用OC有两种方法,第一种为block调用,第二种为JSExport protocol。

案例二:我们在OC中定义了一个如下方法,我们需要在JS中对它进行调用


-(NSInteger)add:(NSInteger)a and:(NSInteger)b{        return  a+b;}


3.1、block调用


-(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);}


3.2、JSExport protocol


第一步:定义一个遵守JSExport的AddJSExport协议。


@protocol AddJSExport //用宏转换下,将JS函数名字指定为add;JSExportAs(add, - (NSInteger)add:(NSInteger)a and:(NSInteger)b);@property (nonatomic, assign) NSInteger sum;@end


第二步:新建一个对象AddJSExportObj,去实现以上协议。


AddJSExportObj.h@interface AddJSExportObj : NSObject@property (nonatomic, assign) NSInteger sum;@endAddJSExportObj.m@implementation AddJSExportObj-(NSInteger)add:(NSInteger)a and:(NSInteger)b{    return a+b;}@end


第三步:在VC中进行JS调用


-(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);}


四、一个从服务端下发JS脚本,执行本地方法的实现思路


案例三:本地定义了一系列方法,可以通过服务端下发js脚本去控制具体去执行那些方法。这样就可以在远端实现对于客户端的控制。


第一步:预置本地方法


-(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");}


第二步:服务端下发脚本


-(NSString *)getJS{        //可以从服务端下发    //return @"execute1()";    return @"execute2()";}


第三步:根据服务端下发脚本执行


-(void)executeByJs{    [self initJS];        NSString *js = [self getJS];    [self.context evaluateScript:js];}


五、JSCore在Web容器中的使用


在UIWebView中,我们可以在- (void)webViewDidFinishLoad:(UIWebView *)webView方法中,通过KVC的方式获取到当前容器的JSContent对象,通过该对象,我们就可以方便的进行hybrid操作。


JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];


案例演示:在html中调研OC代码中的分享功能和调用相机功能。


第一步:HelloWord.html代码如下:


function jsCallNative(){    WBBridge.callCamera();}function jsCallNative2(){    var shareInfo = "分享内容";    var str = WBBridge.share(shareInfo);    alert(str);}<input type="button" onclick="jscallnative()" value="jscallnative" ><input type="button" onclick="jscallnative2()" value="jscallnative2" >
</input type="button" onclick="jscallnative2()" value="jscallnative2" ></input type="button" onclick="jscallnative()" value="jscallnative" >


第二步:实现一个遵守JSExport的协议WebViewJSExport


@protocol WebViewJSExport - (void)callCamera;- (NSString*)share:(NSString*)shareString;@end


第三步:当前VC需要实现WebViewJSExport


@interface ViewController ()<uiwebviewdelegate,webviewjsexport>@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</uiwebviewdelegate,webviewjsexport>


这样我们就可以在webView中调用我们native组建了,实现了一个简单的hybird功能。这就补充了在UIWebView实现hybird功能的方式。


补充


对于WKWebView,目前还没有能够拿到JSContent的对象的方式。


六、参考资料


javascriptcore官方资料

JavaScriptCore 使用

iOS7新JavaScriptCore框架入门介绍