高端品牌网站建设制作需要注意什么,简历模板网站免费,低价网站制作企业,wordpress 宅谈JS与native 交互简单应用一、objectiveC 语法简介二、简易项目浏览器搭建新建项目步骤#xff1a;1DraggedImage.png22222.png333333.png44444.png建立一个小的浏览器即webview关键代码如下#xff1a;// context 上下文也可以在此处获取#xff0c;开始加载…JS与native 交互简单应用一、objectiveC 语法简介二、简易项目浏览器搭建新建项目步骤1DraggedImage.png22222.png333333.png44444.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 如下设置调出开发者工具aaaa.pngbbbbb.pngOK这样我就可以在工具栏中多了一个 【开发】 选项然后我们编译我们的项目就可以找到相应的网页跟调试普通网页相同只是网页现在在手机上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);endinterface JsBindingDemo : NSObject endbinding类 .m 文件#import JsBindingDemo.himplementation JsBindingDemo- (NSInteger)addX:(NSInteger)x andY:(NSInteger)y {return xy;}end我们要用export 的方式去调用我们首先要绑定初始化binding类然后注入到js 中代码如下- (void)initBinding {JsBindingDemo *binding [[JsBindingDemo alloc]init];self.jsbinding_context[JsBindingDemo] binding;}2 native调用js 方法(也有两种方法)acontext 用上下文执行- (JSValue *)evaluateScript:(NSString *)script;eg:执行js中的 native_ execute() 方法[self.jsbinding_context evaluateScript:native_ execute()];b用webview 执行- (JSValue *)evaluateScript:(NSString *)script withSourceURL:(NSURL *)sourceURLeg: [self.webview evaluateScriptnative_ execute() withSourceURL:index.js];- (nullable NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;eg:[self.webView stringByEvaluatingJavaScriptFromString:native_ execute()];备注上面为调用方法代码导出、注入 属性步骤与导出、注入方法代码 相同不一一举例说明五、参考资料