先認識一下 JavascriptCore
JavascriptCore 是 WebKit 的核心組件之一,負責解析 JavaScript 腳本並提供執行環境。從 iOS 7 開始,蘋果把這套能力開放給了 iPhone 平台上的開發者,從此我們不再需要依賴 UIWebView 的 stringByEvaluatingJavaScriptFromString: 這種粗糙的方式,而是可以直接拿到完整的 JS 上下文,雙向調用變得優雅許多。
第一步:建立 WebView 並加載本地 HTML
NSURL* htmlURL = [[NSBundle mainBundle] URLForResource: @"demo" withExtension: @"html"]; [_webView loadRequest: [NSURLRequest requestWithURL: htmlURL]];
示例頁面裡我們要跑通四種最常見的交互場景:
HTML 部分的代碼
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function showAlert(){
alert('OC call JS with no argument');
}
function showAlertWithString(string){
alert(string);
}
function callOCWithArgument() {
jsCallOCWithArgument('參數1 ','參數2 ','參數3');
}
</script>
</head>
<body>
</br>
</br>
</br>
</br>
<form>
<button type='button' onclick='callOC()'>jsCallOC</button>
<button type='button' onclick='callOCWithArgument()'>jsCallOCWithArgument</button>
</form>
</body>
</html>
JS 如何調用 OC
關鍵的一步出現在 WebView 的代理方法 webViewDidFinishLoad: 裡,頁面加載完成後我們才能安全地取出 JS 上下文:
-(void)webViewDidFinishLoad:(UIWebView *)webView {
_context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javascriptContext"];
__weak typeof(self) weakSelf = self;
_context.exceptionHandler = ^(JSContext *context, JSValue *exception) {
weakSelf.context.exception = exception;
};
//js調用OC
_context[@"callOC"] = ^() {
NSArray *args = [JSContext currentArguments];
for (JSValue *jsVal in args) {
NSLog(@"%@", jsVal.toString);
}
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"arguments" message:@"JS Call OC With No Argument" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction * action = [UIAlertAction actionWithTitle:@"Done" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}];
[alertView addAction:action];
[weakSelf presentViewController:alertView animated:YES completion:nil];
});
};
_context[@"jsCallOCWithArgument"] = ^() {
NSArray *args = [JSContext currentArguments];
NSMutableString * stirng = [NSMutableString string];
for (JSValue * value in args) {
[stirng appendString:value.toString];
}
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"arguments" message:stirng preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction * action = [UIAlertAction actionWithTitle:@"Done" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
}];
[alertView addAction:action];
[weakSelf presentViewController:alertView animated:YES completion:nil];
});
};
}
原理其實很直白:我們定義一個 block,把它以字符串為鍵存進 JSContext,這一步等價於在 JS 全局作用域裡聲明了一個同名的 function。之後頁面裡任何位置寫 callOC(),執行的就是我們那個 block 裡的邏輯。
參數的接收依靠 [JSContext currentArguments],它返回一個數組,元素都是 JSValue 對象,取值時調用 toString 即可。
另外提醒一句:block 裡直接操作 UI 需要在主線程執行,所以示例中統一用 dispatch_async 切回主隊列,這是實際項目中很容易踩到的坑。
OC 如何調用 JS
放兩個 Button,在點擊事件裡分別執行:
- (IBAction)callJS:(id)sender {
[_context evaluatescript:@"showAlert()"];
}
- (IBAction)callJSWithArguments:(id)sender {
[_context evaluatescript:@"showAlertWithString('OC call JS with arguments')"];
// 也可以換成下面這種更結構化的寫法
// [_context[@"showAlertWithString"] callWithArguments:@[@"OC call JS with arguments"]];
}
兩種方式各有側重:evaluateScript: 適合執行一段腳本表達式,而 callWithArguments: 更適合把 OC 的對象數組直接映射成 JS 函數的入參,可讀性更好。
小結
JavaScriptCore 讓原生頁面與 H5 頁面之間的通信成本大幅降低:OC 調 JS 用 evaluateScript: 或 callWithArguments:,JS 調 OC 則先把 block 掛到 context 上。掌握這兩個方向,混合開發的骨架就搭起來了。示例工程已整理好,需要的可以下載對照著跑一遍。有疑問歡迎留言交流。