您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發基礎

JavaScriptCore 完全入門:讓 Objective-C 與 JS 雙向呼叫

編輯:iOS 開發基礎

一、簡單介紹

JavaScriptCore(簡稱 JSCore)是蘋果在 iOS 中提供的 framework,讓 Objective-C 與 JavaScript 之間的互操作變得相當便利。它預設不會被加入專案,需要手動添加。

加入之後,可以發現 JavaScriptCore.h 主要包含以下五個檔案:

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

各檔案職責如下:

  • JSContext——代表 JavaScript 的執行環境。你可以在 OC 環境中建立 JSContext 來執行 JavaScript 腳本,也能在腳本中存取 OC 的值與方法。
  • JSValue——OC 與 JavaScript 數值互轉的橋梁,提供大量型別轉換方法,兩者的對應關係如下圖。

  • JSManagedValue——JSValue 的包裝類別,用以輔助 JS 與 OC 物件之間的記憶體管理。JS 採用垃圾回收且物件皆為強引用,OC 則是引用計數;若雙方互相引用就會形成循環引用而洩漏記憶體,用 JSManagedValue 包裝 JSValue 即可避免。
  • JSVirtualMachine——JS 執行的虛擬機,支援多個 JavaScript 環境並行,並負責 JS 與 OC 互轉過程中的記憶體管理。
  • JSExport——一個協定。若希望 JS 能直接呼叫 OC 物件的方法與屬性,只要讓該 OC 物件 conform 這個協定即可。

以下透過實例來熟悉 JSCore 的用法。

二、在 Objective-C 中呼叫 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 中呼叫 Objective-C 方法

有兩種途徑:block 與 JSExport protocol。以下先在 OC 中定義一個待呼叫的方法:

- (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 的協定

@protocol AddJSExport 
// 用巨集把 JS 端的方法名指定為 add
JSExportAs(add, - (NSInteger)add:(NSInteger)a and:(NSInteger)b);
@property (nonatomic, assign) NSInteger sum;
@end

第二步:建立實作該協定的物件

// 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

第三步:在 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];
    // JS 中的 OCAddObj 即對應 OC 中的 AddJSExportObj
    self.context[@"OCAddObj"] = self.addObj;
    [self.context evaluateScript:@"OCAddObj.sum = OCAddObj.add(2,30)"];
    NSLog(@"%zi", self.addObj.sum);
}

四、實作「伺服器下發腳本,驅動本地方法」

案例三:本地預置一系列方法,由伺服器下發 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 @"execute2()";
}

第三步:依腳本執行

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

五、JSCore 在 Web 容器中的應用

在 UIWebView 中,我們可以在 - (void)webViewDidFinishLoad:(UIWebView *)webView 裡透過 KVC 取得當前容器的 JSContext,之後便能方便地進行 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);
}

第二步:定義遵守 JSExport 的協定

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

第三步:讓當前 VC 實作該協定

@interface ViewController () 
@property (nonatomic, strong) JSContext *context;
@property (nonatomic, strong) UIWebView *webView;
@end

@implementation ViewController
- (void)initWebView {
    _webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    _webView.delegate = self;
    [self.view addSubview:_webView];
    NSURL *url = [[NSURL alloc] initWithString:@"https://localhost:8080/myDiary/HelloWorld.html"];
    [_webView loadRequest:[NSURLRequest requestWithURL:url]];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    _context = context;
    // 把本物件橋接給 JS,JS 中的 WBBridge 即代表 self
    [_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 組件,完成一個簡易的 hybrid 功能。這補充了 UIWebView 實現 hybrid 的另一種方式;還有一種常見做法是建立隱藏的 iframe 來攔截請求,可參考「iOS H5 容器的一些探究(一):UIWebView 和 WKWebView 的比較和選擇」。

補充

至於 WKWebView,目前還沒有一勞永逸取得 JSContext 的官方途徑。

六、參考資料

javascriptcore 官方文件
JavaScriptCore 使用
iOS 7 新 JavaScriptCore 框架入門介紹

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved