在app中,經(jīng)常會(huì)嵌入一下HTML 界面,避免不了和JS進(jìn)行一些交互冒掌。
iOS端,經(jīng)常使用的控件是WKWebView和UIWebView蹲盘。
今天我來(lái)簡(jiǎn)單的介紹一下股毫,OC與JS互調(diào)的方法,以下方法應(yīng)該可以滿足各位碼農(nóng)的一般使用召衔!
下面廢話少說(shuō)铃诬,上代碼!2粤荨趣席!
一、WKWebView 與 OC 的互調(diào)
HTML代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" name="viewport" content= width=240, height=320, user-scalable=yes, initial-scale=2.5, maximum-scale=5.0, minimun-scale=1.0>
<title>WkWebView與JS互調(diào)</title>
</head>
<body>
<button onclick="getImage()" style="height:50px;width:100px;"> JS調(diào)用OC </button>
<script type="text/javascript">
<!-- JS調(diào)用OC -->
function getImage() {
window.webkit.messageHandlers.myName.postMessage("JS調(diào)用OC");
}
</script>
<script>
<!-- OC調(diào)用JS -->
function payResult(str){
alert(str);
}
</script>
</body>
</html>
把以上的創(chuàng)建一個(gè)HTML,并把上面的HTML的代碼復(fù)制到里面醇蝴,然后宣肚,把HTML的工程文件復(fù)制到你的工程里面。
創(chuàng)建WKWebView悠栓,并把HTML加載到WKWebView霉涨。
/** 加載HTML */
NSURL *filePath = [[NSBundle mainBundle] URLForResource:@"untitled.html" withExtension:nil];
NSURLRequest *request = [NSURLRequest requestWithURL:filePath];
/** 以下 方法會(huì)接受OC傳給JS 的參數(shù) 之后再打印出來(lái) */
WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc]init];
[theConfiguration.userContentController addScriptMessageHandler:self name:@"myName"];
/** 以上 */
self.wkWeb = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:theConfiguration];
self.wkWeb.backgroundColor = [UIColor redColor];
self.wkWeb.navigationDelegate = self;
self.wkWeb.UIDelegate = self;
self.wkWeb.clipsToBounds = YES;
[self.view addSubview:self.wkWeb];
[self.wkWeb loadRequest:request];
1、OC調(diào)用JS
// 頁(yè)面加載完成之后調(diào)用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
/** 此方法是向JS代碼傳參數(shù) */
NSString * jsStr = [NSString stringWithFormat:@"payResult('%@')",@"OC調(diào)用JS"];
[self.wkWeb evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"==%@----%@",result, error);
}];
}
/**
* 此方法會(huì)接受 JS 的alert
* 但是 JS 的alert 不會(huì)在客戶端彈出闸迷,會(huì)接受到 彈窗要彈出的數(shù)據(jù) 然后可以打印出來(lái)
* OC 調(diào)用 JS
*/
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:([UIAlertAction actionWithTitle:@"確認(rèn)" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler();
}])];
[self presentViewController:alertController animated:YES completion:nil];
}
2嵌纲、JS調(diào)用OC
/**
* 使用此方法的回調(diào)
* WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc]init];
* [theConfiguration.userContentController addScriptMessageHandler:self name:@"myName"];
* JS 調(diào)用 OC
*/
- (void)userContentController:(WKUserContentController *)userContentController
didReceiveScriptMessage:(WKScriptMessage *)message {
NSString *str = message.body;
UIAlertView * messAlert = [[UIAlertView alloc] initWithTitle:nil message:str delegate:nil cancelButtonTitle:@"yes"otherButtonTitles:nil,nil];
[messAlert show];
}
二、UIWebView 與 OC 的互調(diào)
HTML代碼
<html>
<head>
<meta charset="UTF-8"/>
<title>iOS上webView與JS交互的之oc調(diào)用js的demo</title>
<script>
function showTitleMessage(message) {
alert(message);
}
function asdw(str) {
bdgtasdw(str);
}
</script>
</head>
<body>
<h1>下面是網(wǎng)頁(yè)</h1>
<button style = "font-size:50px; background: yellow; height: 150px; width: 350px;" onclick = "asdw('webView JS 調(diào)用 OC');">點(diǎn)擊按鈕js調(diào)用oc</button>
</body>
</html>
1腥沽、OC調(diào)用JS
- (IBAction)UIWebviewOCAndJS:(id)sender {
[self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"showTitleMessage('%@')",@"WebView oc調(diào)用了js的內(nèi)容"]];
}
2逮走、JS調(diào)用OC
- (void)webViewDidFinishLoad:(UIWebView *)webView {
JSContext *content = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
content[@"bdgtasdw"] = ^() {
NSLog(@"js調(diào)用oc---------begin--------");
NSArray *thisArr = [JSContext currentArguments];
dispatch_async(dispatch_get_main_queue(), ^{
for (JSValue *jsValue in thisArr) {
UIAlertView * messAlert = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"%@",jsValue] delegate:nil cancelButtonTitle:@"yes"otherButtonTitles:nil,nil];
[messAlert show];
}
});
NSLog(@"js調(diào)用oc---------The End-------");
};
}
Demo地址
希望以上的內(nèi)容會(huì)對(duì)你有所啟發(fā)!