javascript
c html联调,JS与native 交互简单应用
JS與native 交互簡單應用
一、objectiveC 語法簡介
二、簡易項目瀏覽器搭建
新建項目步驟:
1>
DraggedImage.png
2>
2222.png
3>
33333.png
4>
4444.png
建立一個小的瀏覽器即webview
關鍵代碼如下:
// context 上下文也可以在此處獲取,開始加載網頁調用此方法
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
return YES;
}
// 網頁加載完成會執行此方法
- (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交互聯調工具認識:
iOS 與 js 交互聯調工具必須為safari,首先我們設置一下safari 如下設置調出開發者工具
a'a'a'a.png
bbbbb.png
OK這樣我就可以在工具欄中多了一個 【開發】 選項,然后我們編譯我們的項目就可以找到相應的網頁,跟調試普通網頁相同,只是網頁現在在手機上
DraggedImage-2-1.png
四、js 與 native 原生交互
1> js 調用oc 方法
a> 用block 的方式
self.jsbinding_context[@"multiply"] = ^(NSInteger a, NSInteger b){
return a * b;
};
b> JSExport 方式
binding類 .h 文件
#import
#import
@protocol JsBindingDemoProtocol
JSExportAs(nativeAdd, - (NSInteger)addX:(NSInteger)x andY:(NSInteger)y);
@end
@interface JsBindingDemo : NSObject
@end
binding類 .m 文件
#import "JsBindingDemo.h"
@implementation JsBindingDemo
- (NSInteger)addX:(NSInteger)x andY:(NSInteger)y {
return x+y;
}
@end
我們要用export 的方式去調用,我們首先要綁定初始化binding類,然后注入到js 中,代碼如下:
- (void)initBinding {
JsBindingDemo *binding = [[JsBindingDemo alloc]init];
self.jsbinding_context[@"JsBindingDemo"] = binding;
}
2> native調用js 方法(也有兩種方法)
a>context 用上下文執行
- (JSValue *)evaluateScript:(NSString *)script;
eg:執行js中的 native_ execute() 方法
[self.jsbinding_context evaluateScript:@"native_ execute()"];
b>用webview 執行
- (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()"];
備注:上面為調用方法代碼,導出、注入 屬性,步驟與導出、注入方法代碼 相同不一一舉例說明
五、參考資料:
總結
以上是生活随笔為你收集整理的c html联调,JS与native 交互简单应用的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 文件(视频)上传到阿里云 java实现
- 下一篇: 阵列信号处理 窄带信号与包络
