iOS開發免不了要與UIWebView打交道,然后就要涉及到JS與原生OC交互,今天總結一下JS與原生OC交互的兩種方式。
JS調用原生OC篇(我自己用的方式二,簡單方便)
方式一
第一種方式是用JS發起一個假的URL請求,然后利用UIWebView的代理方法攔截這次請求,然后再做相應的處理。
我寫了一個簡單的HTML網頁和一個btn點擊事件用來與原生OC交互,HTML代碼如下:
<html>
<header>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function showAlert(message){
alert(message);
}
function loadURL(url) {
var iFrame;
iFrame = document.createElement("iframe");
iFrame.setAttribute("src", url);
iFrame.setAttribute("style", "display:none;");
iFrame.setAttribute("height", "0px");
iFrame.setAttribute("width", "0px");
iFrame.setAttribute("frameborder", "0");
document.body.appendChild(iFrame);
// 發起請求后這個 iFrame 就沒用了,所以把它從 dom 上移除掉
iFrame.parentNode.removeChild(iFrame);
iFrame = null;
}
function firstClick() {
loadURL("firstClick://shareClick?title=分享的標題&content=分享的內容&url=鏈接地址&imagePath=圖片地址");
}
</script>
</header>
<body>
<h2> 這里是第一種方式 </h2>
<br/>
<br/>
<button type="button" onclick="firstClick()">Click Me!</button>
</body>
</html>
然后在項目的控制器中實現UIWebView的代理方法:
#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL * url = [request URL];
if ([[url scheme] isEqualToString:@"firstclick"]) {
NSArray *params =[url.query componentsSeparatedByString:@"&"];
NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];
for (NSString *paramStr in params) {
NSArray *dicArray = [paramStr componentsSeparatedByString:@"="];
if (dicArray.count > 1) {
NSString *decodeValue = [dicArray[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[tempDic setObject:decodeValue forKey:dicArray[0]];
}
}
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"方式一" message:@"這是OC原生的彈出窗" delegate:self cancelButtonTitle:@"收到" otherButtonTitles:nil];
[alertView show];
NSLog(@"tempDic:%@",tempDic);
return NO;
}
return YES;
}
注意:1. JS中的firstClick,在攔截到的url scheme全都被轉化為小寫。
2.html中需要設置編碼,否則中文參數可能會出現編碼問題。
3.JS用打開一個iFrame的方式替代直接用document.location的方式,以避免多次請求,被替換覆蓋的問題。
早期的JS與原生交互的開源庫很多都是用得這種方式來實現的,例如:PhoneGap、WebViewJavascriptBridge。關於這種方式調用OC方法,唐巧早期有篇文章有過介紹:
關於UIWebView和PhoneGap的總結
方式二
在iOS 7之后,apple添加了一個新的庫JavaScriptCore,用來做JS交互,因此JS與原生OC交互也變得簡單了許多。
首先導入JavaScriptCore庫, 然后在OC中獲取JS的上下文
JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
再然后定義好JS需要調用的方法,例如JS要調用share方法:
則可以在UIWebView加載url完成后,在其代理方法中添加要調用的share方法:
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//定義好JS要調用的方法, share就是調用的share方法名
context[@"share"] = ^() {
NSLog(@"+++++++Begin Log+++++++");
NSArray *args = [JSContext currentArguments];
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"方式二" message:@"這是OC原生的彈出窗" delegate:self cancelButtonTitle:@"收到" otherButtonTitles:nil];
[alertView show];
});
for (JSValue *jsVal in args) {
NSLog(@"%@", jsVal.toString);
}
NSLog(@"-------End Log-------");
};
}
注意:
可能最新版本的iOS系統做了改動,現在(iOS9,Xcode 7.3,去年使用Xcode 6 和iOS 8沒有線程問題)中測試,block中是在子線程,因此執行UI操作,控制台有警告,需要回到主線程再操作UI。
其中相對應的html部分如下:
<html>
<header>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function secondClick() {
share('分享的標題','分享的內容','圖片地址');
}
function showAlert(message){
alert(message);
}
</script>
</header>
<body>
<h2> 這里是第二種方式 </h2>
<br/>
<br/>
<button type="button" onclick="secondClick()">Click Me!</button>
</body>
</html>
JS部分確實要簡單的多了。
OC調用JS篇
方式一
NSString *jsStr = [NSString stringWithFormat:@"showAlert('%@')",@"這里是JS中alert彈出的message"];
[_webView stringByEvaluatingJavaScriptFromString:jsStr];
注意:該方法會同步返回一個字符串,因此是一個同步方法,可能會阻塞UI。
方式二
繼續使用JavaScriptCore庫來做JS交互。
JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
NSString *textJS = @"showAlert('這里是JS中alert彈出的message')";
[context evaluateScript:textJS];
重點:
stringByEvaluatingJavaScriptFromString
是一個同步的方法,使用它執行JS方法時,如果JS 方法比較耗的時候,會造成界面卡頓。尤其是js 彈出alert 的時候。
alert 也會阻塞界面,等待用戶響應,而stringByEvaluatingJavaScriptFromString
又會等待js執行完畢返回。這就造成了死鎖。
官方推薦使用WKWebView
的evaluateJavaScript:completionHandler:
代替這個方法。
其實我們也有另外一種方式,自定義一個延遲執行alert 的方法來防止阻塞,然后我們調用自定義的alert 方法。同理,耗時較長的js 方法也可以放到setTimeout 中。function asyncAlert(content) { setTimeout(function(){ alert(content); },1); }
我也寫了一個demo,包括JS與OC交互的兩種方式。
JS_OC_summary
如果你看的還不盡興,后面還有幾篇JS相互調用的文章。
iOS下JS與OC互相調用(一)--UIWebView 攔截URL
iOS下JS與OC互相調用(二)--WKWebView 攔截URL
iOS下JS與OC互相調用(三)--MessageHandler
iOS下JS與OC互相調用(四)--JavaScriptCore
iOS下JS與OC互相調用(五)--UIWebView + WebViewJavascriptBridge
iOS下JS與OC互相調用(六)--WKWebView + WebViewJavascriptBridge
iOS下JS與OC互相調用(七)--Cordova 基礎
iOS下JS與OC互相調用(八)--Cordova詳解+實戰
剩下的幾篇未完待續。
作者:Haley_Wong
鏈接:http://www.jianshu.com/p/d19689e0ed83
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。