利用JavaScriptCore實現OC和JS交互

JavaScriptCore

JavaScriptCore是webkit的一個重要組成部分,主要是對JS進行解析和提供執(zhí)行環(huán)境。iOS7后蘋果在iPhone平臺推出,極大的方便了我們對js的操作。

首先創(chuàng)建webView,讀取本地的html文件
 NSURL* htmlURL = [[NSBundle mainBundle] URLForResource: @"demo" withExtension: @"html"];
[_webView loadRequest: [NSURLRequest requestWithURL: htmlURL]];

在demo中,我們要實現4種情況

  • JS調用OC
  • JS調用OC并傳遞參數
  • OC調用JS
  • OC調用JS并傳遞參數

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中

-(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,然后保存到context里面,其實就是轉換成了JS中命名為callOC的function。然后我們直接執(zhí)行這個function,調用的就是我們的block里面的內容了。
傳過來的參數可以通過[JSContext currentArguments]這個array接受,里面是JSValue對象。

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"]];
}

即可實現OC調用JS。

demo已上傳到github,需要的可以看一下。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 隨著H5技術的興起,在iOS開發(fā)過程中,難免會遇到原生應用需要和H5頁面交互的問題。其中會涉及方法調用及參數傳值等...
    Chris_js閱讀 3,245評論 1 8
  • 前言 Web 頁面中的 JS 與 iOS Native 如何交互是每個 iOS 猿必須掌握的技能。而說到 Nati...
    幽城88閱讀 2,342評論 1 8
  • 前言### 最近公司項目進行比較激烈,沒有時間寫demo,但是時間就像是海綿里的水,擠擠總是會有的。在公司的項目中...
    摸著石頭過河_崖邊樹閱讀 2,365評論 2 14
  • 寫在前面 本篇文章是對我一次組內分享的整理,大部分圖片都是直接從keynote上截圖下來的,本來有很多炫酷動效的,...
    等開會閱讀 14,727評論 6 69
  • 本文由我們團隊的 糾結倫 童鞋撰寫。 寫在前面 本篇文章是對我一次組內分享的整理,大部分圖片都是直接從keynot...
    知識小集閱讀 15,387評論 11 172

友情鏈接更多精彩內容