1.用本地的html来测试,先写一个html
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>oc与js交互</title>
<script type="text/javascript" src="index.js"></script>
</head>
<body>
<button onclick="hello()">这是按钮</button>
<button id="button" onclick="buttonFun('传参') ">这是按钮1</button>
</body>
</html>
index.js:
function hello() {
alert("hello")
}
var param = "demo";
function buttonFun(param){
alert(param)
}
在.m导入
#import <JavaScriptCore/JavaScriptCore.h>
加载本地的html
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
NSString * htmlPath = [[NSBundle mainBundle] pathForResource:@"index"
ofType:@"html"];
NSString * htmlCont = [NSString stringWithContentsOfFile:htmlPath
encoding:NSUTF8StringEncoding
error:nil];
[self.webView loadHTMLString:htmlCont baseURL:baseURL];
self.webView.delegate = self;
3.交互
思路:
1.先和前端同事规定好函数名称和传参的类型
2.通过函数名,来进行oc的代码操作
3.oc代码操作结束后,把结果传给h5
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
//网页加载完成调用此方法
//首先创建JSContext 对象(此处通过当前webView的键获取到jscontext)
JSContext *context=[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//获取函数名称
context[@"hello"] = ^(){
//进行iOS这边的逻辑操作
NSLog(@"_____get identify__________");
//操作结束,把结果传给h5 buttonFun为接受结果的函数名称
NSString *smethods = [NSString stringWithFormat:@"%@('%@')", @"buttonFun", @"打印结束"];
[webView stringByEvaluatingJavaScriptFromString:smethods];
};
}
CE23FC8B-E460-4873-9A0B-9FF1DD2956C8.png
网友评论