iOS下JS與原生OC互相調(diào)用(總結(jié))
iOS開發(fā)免不了要與UIWebView打交道鹃共,然后就要涉及到JS與原生OC交互供汛,今天總結(jié)一下JS與原生OC交互的兩種方式岖常。JS調(diào)用原生OC篇方式一第一種方式是用JS發(fā)起一個(gè)假的URL請(qǐng)求钞脂,然后利用UIWebView的代理方法攔截這次請(qǐng)求纵散,然后再做相應(yīng)的處理。我寫了一個(gè)簡單的HTML網(wǎng)頁和一個(gè)btn點(diǎn)擊事件用來與原生OC交互人芽,HTML代碼如下:
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);
// 發(fā)起請(qǐng)求后這個(gè) iFrame 就沒用了望几,所以把它從 dom 上移除掉
iFrame.parentNode.removeChild(iFrame);
iFrame = null;
}
function firstClick() {
loadURL("firstClick://shareClick?title=分享的標(biāo)題&content=分享的內(nèi)容&url=鏈接地址&imagePath=圖片地址");
}
這里是第一種方式
Click Me!然后在項(xiàng)目的控制器中實(shí)現(xiàn)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;
}
注意:
- JS中的firstClick,在攔截到的url scheme全都被轉(zhuǎn)化為小寫。
2.html中需要設(shè)置編碼萤厅,否則中文參數(shù)可能會(huì)出現(xiàn)編碼問題橄抹。
3.JS用打開一個(gè)iFrame的方式替代直接用document.location的方式靴迫,以避免多次請(qǐng)求,被替換覆蓋的問題楼誓。
早期的JS與原生交互的開源庫很多都是用得這種方式來實(shí)現(xiàn)的玉锌,例如:PhoneGap、WebViewJavascriptBridge疟羹。
關(guān)于這種方式調(diào)用OC方法主守,唐巧早期有篇文章有過介紹:
關(guān)于UIWebView和PhoneGap的總結(jié)方式二在iOS 7之后,apple添加了一個(gè)新的庫JavaScriptCore阁猜,用來做JS交互丸逸,因此JS與原生OC交互也變得簡單了許多。
首先導(dǎo)入JavaScriptCore庫, 然后在OC中獲取JS的上下文
JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
再然后定義好JS需要調(diào)用的方法剃袍,例如JS要調(diào)用share方法:
則可以在UIWebView加載url完成后,在其代理方法中添加要調(diào)用的share方法:
- (void)webViewDidFinishLoad:(UIWebView *)webView{
JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//定義好JS要調(diào)用的方法, share就是調(diào)用的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系統(tǒng)做了改動(dòng)捎谨,現(xiàn)在(iOS9民效,Xcode 7.3,去年使用Xcode 6 和iOS 8沒有線程問題)中測(cè)試,block中是在子線程涛救,因此執(zhí)行UI操作畏邢,控制臺(tái)有警告,需要回到主線程再操作UI检吆。
其中相對(duì)應(yīng)的html部分如下:
function secondClick() {
share('分享的標(biāo)題','分享的內(nèi)容','圖片地址');
}
function showAlert(message){
alert(message);
}
這里是第二種方式
Click Me!JS部分確實(shí)要簡單的多了舒萎。
OC調(diào)用JS篇方式一
NSString *jsStr = [NSString stringWithFormat:@"showAlert('%@')",@"這里是JS中alert彈出的message"];
[_webView stringByEvaluatingJavaScriptFromString:jsStr];
注意:該方法會(huì)同步返回一個(gè)字符串,因此是一個(gè)同步方法蹭沛,可能會(huì)阻塞UI臂寝。方式二繼續(xù)使用JavaScriptCore庫來做JS交互。
JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
NSString *textJS = @"showAlert('這里是JS中alert彈出的message')";
[context evaluateScript:textJS];
重點(diǎn):
stringByEvaluatingJavaScriptFromString是一個(gè)同步的方法摊灭,使用它執(zhí)行JS方法時(shí)咆贬,如果JS 方法比較耗的時(shí)候,會(huì)造成界面卡頓帚呼。
尤其是js 彈出alert 的時(shí)候掏缎。
alert 也會(huì)阻塞界面,等待用戶響應(yīng)煤杀,而stringByEvaluatingJavaScriptFromString又會(huì)等待js執(zhí)行完畢返回眷蜈。這就造成了死鎖。
官方推薦使用WKWebView的evaluateJavaScript:completionHandler:代替這個(gè)方法沈自。
其實(shí)我們也有另外一種方式酌儒,自定義一個(gè)延遲執(zhí)行alert 的方法來防止阻塞,然后我們調(diào)用自定義的alert 方法酥泛。
同理今豆,耗時(shí)較長的js 方法也可以放到setTimeout 中嫌拣。
function asyncAlert(content) {
setTimeout(function(){
alert(content);
},1);
}