JS调用OC方法(JavaScriptCore)
2016-03-06 15:35
375 查看
一、JS 与OC交互一种方式是通过在JS与OC间定义一个协议,通过UIWebView的代理方法
根据相应协议来实现JS向OC的传值过程。
通过协议传值(方法一)
二、JS 与OC交互的另一种方式是通过OC的JavaScriptCore框架
实现过程:
1、OC
2、html代码
-(BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
根据相应协议来实现JS向OC的传值过程。
通过协议传值(方法一)
二、JS 与OC交互的另一种方式是通过OC的JavaScriptCore框架
实现过程:
1、OC
UIWebView *webView=[[UIWebView alloc]initWithFrame:self.view.bounds]; NSString *path=[[NSBundle mainBundle]pathForResource:@"test" ofType:@"html"]; NSURL *url=[NSURL fileURLWithPath:path]; NSURLRequest *request=[NSURLRequest requestWithURL:url]; [webView loadRequest:request]; [self.view addSubview:webView]; //得到JSContext对象 JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; context[@"zwlog"] = ^() { //获取参数 NSArray *args = [JSContext currentArguments]; //打印内容 for (JSValue *jsvalue in args) { NSLog(@"%@", jsvalue); } }; self.webView=webView;
//第二中加载方式: NSString *path=[[NSBundle mainBundle]pathForResource:@"test" ofType:@"html"]; NSString *htmlString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; NSURL *url=[NSURL fileURLWithPath:path]; [webView loadHTMLString:htmlString baseURL:url];
2、html代码
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <script type="text/javascript"> function callOC(value1,value2){ zwlog(value1+","+value2); } </script> <body bgcolor="#a9a9a9"> <div style="text-align: center;margin-top: 50px"> <input type="button" value="确定" onClick="callOC('11111','1')" /> </div> </body> </html>
相关文章推荐
- 201603061528_《Javascript交换两个变量值(不借用第三变量)》
- threejs使用概述
- 201603061520_《Javascript生成随机字符串函数(可用于加密)》
- JavaScript加载XMl文件
- 使用jstack 发现死锁
- js 去掉字符串前后空格
- js判断undefined类型
- 3、JS中的语句
- JavaScript模拟数组合并concat
- js 添加二維數組
- JavaScript模拟push
- 2、JS中的表达式和运算符
- javascript实现网页定时跳转代码
- JavaScript学习笔记(8)——JavaScript语法之运算符
- JavaScript学习笔记(7)——JavaScript语法之函数
- JavaScript编写的几个训练逻辑思维能力的算法
- JavaScript学习笔记(6)——JavaScript语法之对象
- JavaScript学习笔记(5)——JavaScript语法之数据类型
- iOS开发:JavaScriptCore.framework的简单使用--JS与OC的交互篇
- JS思维之路菜鸟也能有大能量(2)--模拟数组合并concat