IOS JavaScriptCore介紹

來源:互聯網
上載者:User

標籤:call   net   shu   標頭檔   方法   app   tail   arguments   函數   

本文主要轉自:https://www.jianshu.com/p/cdaf9bc3d65d

                     http://blog.csdn.net/u011993697/article/details/51577295

oc與JS的互動實現方式有很多,在ios7之前用的比較多的是WebViewJavaScriptBridge,在ios7之後蘋果將JavaScriptCore架構開放,這樣就增加一種選擇。

1、準備工作

首先要匯入JavaScriptCore的標頭檔

#import <JavaScriptCore/JavaScriptCore.h>

2、用webview載入HTML檔案,這裡用的是本地html

- (void)viewDidLoad{[super viewDidLoad];NSString *path = [[[NSBundle mainBundle] bundlePath]  stringByAppendingPathComponent:@"JSCallOC.html"];NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]];[self.webView loadRequest:request];}

3、在進行JS互動之前,需要通過JSContent建立一個使用JS的環境

- (void)webViewDidFinishLoad:(UIWebView *)webView{    // Undocumented access to UIWebView‘s JSContext    self.context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];        // 列印異常    self.context.exceptionHandler =    ^(JSContext *context, JSValue *exceptionValue)    {        context.exception = exceptionValue;        NSLog(@"%@", exceptionValue);    };           }

4、JS調用OC代碼

4.1、通過block調用

<input type="button" value="測試log" onclick="log(‘測試‘);" />
self.context[@"log"] = ^(NSString *str){NSLog(@"%@", str);};

4.2、實現JSExport協議

定義需要暴露給JS的內容

<input type="button" value="計算階乘" onclick="native.calculateForJS(input.value);" />
@protocol TestJSExport <JSExport>JSExportAs(calculateForJS , - (void)handleFactorialCalculateWithNumber:(NSNumber *)number );@end
 // 以 JSExport 協議關聯 native 的方法self.content[@"native"] = self;

5、OC調用JS代碼

在OC中,所有表示JS中對象,都用JSValue來建立,通過objectForKeyedSubscript方法或者直接使用下標的方法擷取JS對象,然後使用callWithArguments方法來執行函數。

// 方法一.   JSValue *function = [self.context objectForKeyedSubscript:@"factorial"];// 方法二.JSValue * function = self.context[@"factorial"];JSValue *result = [function callWithArguments:@[inputNumber]];self.showLable.text = [NSString stringWithFormat:@"%@", [result toNumber]];

一個demon串連:https://github.com/shaojiankui/JavaScriptCore-Demo

6、封裝

將javascriptcore進行封裝,更方便ios 和 前端進行資料的互動和方法的調用,使用方式和webviewjavascriptbridge一樣,先在plist檔案配置,對外暴露的oc介面需要實現指定的協議。 
demo:https://github.com/HZQuan/WebViewJavaScriptCoreBridge

IOS JavaScriptCore介紹

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.