OC调JS方法并传值
html示例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div style="margin-top: 20px">
<h2>JS与OC交互</h2>
<p>正在跳转...</p>
</div>
<script>
var Callback = function(username,usertel)
{
alert("http://192.168.0.68:8080/hqld/aa_10_10.html?a="+ username +"&b="+ usertel +"");
window.location.href="http://192.168.0.68:8080/hqld/aa_10_10.html?a="+ username +"&b="+ usertel +"";
}
</script>
</body>
</html>
创建UIWebView并load对应的Html
该html源码用于获取oc中的值,并传递到固定的链接中,然后执行自动跳转
使用iOS自带JavaScriptCode框架
关于UIWebView与JS的相互关联
- JSContext:给JavaScript提供运行的上下文环境
- JSValue:JavaScript和Objective-C数据和方法的桥梁
#import <JavaScriptCore/JavaScriptCore.h>
- (void)webViewDidFinishLoad:(UIWebView *)webView {
self.jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
用于捕获错误信息
self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
context.exception = exceptionValue;
NSLog(@"异常信息:%@", exceptionValue);
};
[self call];
}
- (void)call{
// 之后在回调js的方法Callback把内容传出去
JSValue *Callback = self.jsContext[@"Callback"];
//传值给web端
[Callback callWithArguments:@[@"jh",@"15757166666"]];
}