c html联调,JS与native 交互简单应用

JS与native 交互简单应用

一、objectiveC 语法简介

二、简易项目浏览器搭建

新建项目步骤:

1>

04cfa7e7e6e3

DraggedImage.png

2>

04cfa7e7e6e3

2222.png

3>

04cfa7e7e6e3

33333.png

4>

04cfa7e7e6e3

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 如下设置调出开发者工具

04cfa7e7e6e3

a'a'a'a.png

04cfa7e7e6e3

bbbbb.png

OK这样我就可以在工具栏中多了一个 【开发】 选项,然后我们编译我们的项目就可以找到相应的网页,跟调试普通网页相同,只是网页现在在手机上

04cfa7e7e6e3

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()"];

备注:上面为调用方法代码,导出、注入 属性,步骤与导出、注入方法代码 相同不一一举例说明

五、参考资料:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值