UIWebView中OC與JS的傳統(tǒng)交互方式特別簡(jiǎn)單
1. 這里準(zhǔn)備了一個(gè)本地的index.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>OC與JS交互</title>
<script>
function showAlert(name){
alert(name);
return function handle(str){
alert('我是一個(gè)彈窗'+name+str);
return name + '返回給OC';
}
}
</script>
</head>
<body>
<a href="lgedu:///getSum/helloword/js">點(diǎn)擊跳轉(zhuǎn)響應(yīng)OC方法</a>
<a href="lgedu://getPlus/helloword/js">點(diǎn)擊跳轉(zhuǎn)效應(yīng)</a>
<form id="myform" action="lgedu://www.baidu.com/hello/j/Users/spirej/Desktop/OCJS/index.htmls" method="get">
<input id="submit" type="submit" value="我是提交">
</form>
<input type="button" value="彈框" onclick="showAlert('hello JS')"><br/>
</body>
</html>
2. JS調(diào)用OC
// 加載所有請(qǐng)求數(shù)據(jù),以及控制是否加載
// JS 調(diào)用 OC --> shouldStartLoadWithRequest
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSLog(@"scheme = %@", request.URL.scheme); // 標(biāo)示 我們自己的協(xié)議
NSLog(@"host = %@", request.URL.host); // 方法名
NSLog(@"pathComponents = %@", request.URL.pathComponents); // 參數(shù)
// JS 調(diào)用OC 的原理就是 攔截URL
NSString *scheme = request.URL.scheme;
if ([scheme isEqualToString:@"lgedu"]) {
NSArray *array = request.URL.pathComponents;
if (array.count > 1) {
NSString *methodName = array[1];
if ([methodName isEqualToString:@"getSum"]) {
[self performSelector:NSSelectorFromString(methodName) withObject:array afterDelay:0];
//...
}
}
}
return YES;
}
JS調(diào)用OC就是UIWebViewDelegate的這個(gè)代理方法shouldStartLoadWithRequest,其實(shí)質(zhì)就是 攔截URL,解析URL并找到事先約定好的標(biāo)識(shí),時(shí)候判斷實(shí)現(xiàn)相應(yīng)的業(yè)務(wù)邏輯處理。
下面這些都是JS響應(yīng)的樣式,都會(huì)回到UIWebViewDelegate的這個(gè)方法來
UIWebViewNavigationTypeLinkClicked, 點(diǎn)擊
UIWebViewNavigationTypeFormSubmitted, 提交
UIWebViewNavigationTypeBackForward, 返回
UIWebViewNavigationTypeReload, 刷新
UIWebViewNavigationTypeFormResubmitted, 重復(fù)提交
UIWebViewNavigationTypeOther 其他
3. OC調(diào)用JS
- (nullable NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;
OC調(diào)用JS就是實(shí)現(xiàn)UIWebView的這個(gè)方法stringByEvaluatingJavaScriptFromString,傳一個(gè)字符串可以是JS里面寫的方法名。
文中所有示例demo可以在這里下載
https://github.com/SPIREJ/OCJS