一、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>