JSCore的基本使用

1、簡單介紹

JSCore全稱爲JavaScriptCore,是蘋果公司在iOS中加入的一個新的framework。該framework爲OC與JS代碼相互操做的提供了極大的便利。該工程默認是沒有導入工程中的,須要咱們手動添加。javascript

圖片描述

添加完成後,咱們能夠看到JavaScriptCore.h中包含如下5個主要的文件。php

#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的數據類型進行相互轉化。其一一對應關係以下表所示:html

圖片描述

JSManagedValue:JSValue的包裝類。JS和OC對象的內存管理輔助對象。因爲JS內存管理是垃圾回收,而且JS中的對象都是強引用,而OC是引用計數。若是雙方相互引用,勢必會形成循環引用,而致使內存泄露。咱們能夠用JSManagedValue保存JSValue來避免。
JSVirtualMachine: JS運行的虛擬機。能夠支持並行的JavaScript執行,管理JavaScript和OC轉換中的內存管理。
JSExport:一個協議,若是JS對象想直接調用OC對象裏面的方法和屬性,那麼這個OC對象只要實現這個JSExport協議就能夠了。
下面咱們經過實例案例來學習JSCore的用法。java

推薦一個iOS高級交流羣:624212887,羣文件自行下載,無論你是小白仍是大牛熱烈歡迎進羣 ,分享面試經驗,討論技術, 你們一塊兒交流學習成長!但願幫助開發者少走彎路。——點擊:加入ios

2、OC中調用JS方法

案例一:我在js中定義了一個函數add(a,b),咱們須要在OC中進行調用。web

-(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);
}複製代碼

3、JS中調用OC方法

JS中調用OC有兩種方法,第一種爲block調用,第二種爲JSExport protocol。
案例二:咱們在OC中定義了一個以下方法,咱們須要在JS中對它進行調用面試

-(NSInteger)add:(NSInteger)a and:(NSInteger)b{
    return  a+b;
}複製代碼

3.一、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.二、JSExport protocol

第一步:定義一個遵照JSExport的AddJSExport協議。bash

@protocol AddJSExport <JSExport>
//用宏轉換下,將JS函數名字指定爲add;
JSExportAs(add, - (NSInteger)add:(NSInteger)a and:(NSInteger)b);
@property (nonatomic, assign) NSInteger sum;
@end複製代碼

第二步:新建一個對象AddJSExportObj,去實現以上協議。網絡

AddJSExportObj.h
@interface AddJSExportObj : NSObject<AddJSExport>
@property (nonatomic, assign) NSInteger sum;
@end
AddJSExportObj.m
@implementation AddJSExportObj
-(NSInteger)add:(NSInteger)a and:(NSInteger)b{
    return a+b;
}
@end複製代碼

第三步:在VC中進行JS調用app

-(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);
}複製代碼

4、一個從服務端下發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];
}複製代碼

5、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" />
<br/>
<input type="button" onclick="jsCallNative2()" value="jsCallNative2" />
<br/>複製代碼

第二步:實現一個遵照JSExport的協議WebViewJSExport

@protocol WebViewJSExport <JSExport>
- (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複製代碼

這樣咱們就能夠在webView中調用咱們native組建了,實現了一個簡單的hybird功能。這就補充了在UIWebView實現hybird功能的方式。還有一種方式就是iOS H5容器的一些探究(一):UIWebView和WKWebView在的比較和選擇一文中見過的加載隱藏iframe,來攔截請求的方式。

補充
對於WKWebView,目前尚未可以拿到JSContent的對象的方式。

6、參考資料

javascriptcore官方資料

JavaScriptCore 使用

iOS7新JavaScriptCore框架入門介紹

7、聯繫方式

推薦一個iOS高級交流羣:624212887,羣文件自行下載,無論你是小白仍是大牛熱烈歡迎進羣 ,分享面試經驗,討論技術, 你們一塊兒交流學習成長!但願幫助開發者少走彎路。——點擊:加入

若是以爲對你還有些用,就關注小編+喜歡這一篇文章。你的支持是我繼續的動力。

下篇文章預告:Weex開發之路(一):開發環境搭建

文章來源於網絡,若有侵權,請聯繫小編刪除。

相關文章
相關標籤/搜索