1.用本地的html來(lái)測(cè)試,先寫一個(gè)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導(dǎo)入
#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.先和前端同事規(guī)定好函數(shù)名稱和傳參的類型
2.通過(guò)函數(shù)名,來(lái)進(jìn)行oc的代碼操作
3.oc代碼操作結(jié)束后继准,把結(jié)果傳給h5
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
//網(wǎng)頁(yè)加載完成調(diào)用此方法
//首先創(chuàng)建JSContext 對(duì)象(此處通過(guò)當(dāng)前webView的鍵獲取到j(luò)scontext)
JSContext *context=[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//獲取函數(shù)名稱
context[@"hello"] = ^(){
//進(jìn)行iOS這邊的邏輯操作
NSLog(@"_____get identify__________");
//操作結(jié)束移必,把結(jié)果傳給h5 buttonFun為接受結(jié)果的函數(shù)名稱
NSString *smethods = [NSString stringWithFormat:@"%@('%@')", @"buttonFun", @"打印結(jié)束"];
[webView stringByEvaluatingJavaScriptFromString:smethods];
};
}