JS與native 交互簡(jiǎn)單應(yīng)用
先提供一下 demo 下載地址:https://github.com/xiaoma0304/WebDemo.git
一、objectiveC 語(yǔ)法簡(jiǎn)介
http://www.runoob.com/ios/ios-objective-c.html
二围苫、簡(jiǎn)易項(xiàng)目瀏覽器搭建
新建項(xiàng)目步驟:
1>
2>
3>
4>
- 建立一個(gè)小的瀏覽器即webview
關(guān)鍵代碼如下:
// context 上下文也可以在此處獲取裤园,開(kāi)始加載網(wǎng)頁(yè)調(diào)用此方法
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
return YES;
}
// 網(wǎng)頁(yè)加載完成會(huì)執(zhí)行此方法
- (void)webViewDidFinishLoad:(UIWebView *)webView {
self.jsbinding_context = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
[self initBinding];
}
/** 懶加載 */
- (UIWebView *)webView {
if(!_webView) {
_webView = [[UIWebView alloc]init];
_webView.delegate = self;
NSString *path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
NSURL* url = [NSURL fileURLWithPath:path];
// NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"];
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
[_webView loadRequest:request];
}
return _webView;
}
三、js和native交互聯(lián)調(diào)工具認(rèn)識(shí):
iOS 與 js 交互聯(lián)調(diào)工具必須為safari剂府,首先我們?cè)O(shè)置一下safari 如下設(shè)置調(diào)出開(kāi)發(fā)者工具
OK這樣我就可以在工具欄中多了一個(gè) 【開(kāi)發(fā)】 選項(xiàng)拧揽,然后我們編譯我們的項(xiàng)目就可以找到相應(yīng)的網(wǎng)頁(yè),跟調(diào)試普通網(wǎng)頁(yè)相同腺占,只是網(wǎng)頁(yè)現(xiàn)在在手機(jī)上
四淤袜、js 與 native 原生交互
1> js 調(diào)用oc 方法
a> 用block 的方式
self.jsbinding_context[@"multiply"] = ^(NSInteger a, NSInteger b){
return a * b;
};
b> JSExport 方式
binding類(lèi) .h 文件
#import <Foundation/Foundation.h>
#import <JavaScriptCore/JavaScriptCore.h>
@protocol JsBindingDemoProtocol <JSExport>
JSExportAs(nativeAdd, - (NSInteger)addX:(NSInteger)x andY:(NSInteger)y);
@end
@interface JsBindingDemo : NSObject <JsBindingDemoProtocol>
@end
binding類(lèi) .m 文件
#import "JsBindingDemo.h"
@implementation JsBindingDemo
- (NSInteger)addX:(NSInteger)x andY:(NSInteger)y {
return x+y;
}
@end
我們要用export 的方式去調(diào)用,我們首先要綁定初始化binding類(lèi)衰伯,然后注入到j(luò)s 中铡羡,代碼如下:
- (void)initBinding {
JsBindingDemo *binding = [[JsBindingDemo alloc]init];
self.jsbinding_context[@"JsBindingDemo"] = binding;
}
2> native調(diào)用js 方法(也有兩種方法)
a>context 用上下文執(zhí)行
- (JSValue *)evaluateScript:(NSString *)script;
eg:執(zhí)行js中的 native_ execute() 方法
[self.jsbinding_context evaluateScript:@"native_ execute()"];
b>用webview 執(zhí)行
- (JSValue *)evaluateScript:(NSString *)script withSourceURL:(NSURL *)sourceURL
eg: [self.webview evaluateScript@"native_ execute()" withSourceURL:@"index.js"];
- (nullable NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;
eg:[self.webView stringByEvaluatingJavaScriptFromString:@"native_ execute()"];
備注:上面為調(diào)用方法代碼,導(dǎo)出意鲸、注入 屬性烦周,步驟與導(dǎo)出、注入方法代碼 相同不一一舉例說(shuō)明
五怎顾、參考資料:
一份走心的JS-Native交互電子書(shū)
鏈接: https://pan.baidu.com/s/1zhw9ITBT8E_XYgD7dO4DtA 提取碼: nabu