JS调用OC方法(JavaScriptCore)
来源:互联网 发布:苹果5怎么改成4g网络 编辑:程序博客网 时间:2024/05/21 19:29
一、JS 与OC交互一种方式是通过在JS与OC间定义一个协议,通过UIWebView的代理方法 -(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>
1 0
- JS调用OC方法(JavaScriptCore)
- OC调用js(JavaScriptCore)
- iOS js oc相互调用(JavaScriptCore)
- iOS js oc相互调用(JavaScriptCore)
- iOS js oc相互调用(JavaScriptCore)
- iOS js oc相互调用(JavaScriptCore)
- iOS js oc相互调用(JavaScriptCore)
- iOS js oc相互调用(JavaScriptCore)
- iOS js oc相互调用(JavaScriptCore)
- iOS js oc相互调用(JavaScriptCore)
- iOS js oc相互调用(JavaScriptCore)
- iOS js oc相互调用(JavaScriptCore)
- iOS js oc相互调用(JavaScriptCore)
- iOS js oc相互调用(JavaScriptCore)
- iOS js oc相互调用(JavaScriptCore)
- iOS js oc相互调用(JavaScriptCore)(二)
- iOS js oc相互调用(JavaScriptCore)(二)
- iOS js oc相互调用(JavaScriptCore)(二)
- java 内部类总结
- 边看书边做边发挥-图书软件-9
- hdoj 5636 Shortest Path
- Eclipse创建Maven项目提示缺少maven-resources-plugin:2.6
- bzoj4011: [HNOI2015]落忆枫音
- JS调用OC方法(JavaScriptCore)
- 深度学习资料汇总
- linux 查看端口号占用情况
- 数据结构与算法系列----直插,快排,堆排,归并排序讲解
- Android UI优化
- [LeetCode]62. Unique Paths
- uml 关联相关设计模式描述
- 第二周上机实践项目——项目1-宣告“主权”
- CSS3animation动画 + 动画如何切换