第一種方式是用JS發起一個假的URL請求,而後利用UIWebView的代理方法攔截此次請求,而後再作相應的處理。
我寫了一個簡單的HTML網頁和一個btn點擊事件用來與原生OC交互,HTML代碼以下:javascript
<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的代理方法:html
#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的總結java
在iOS 7以後,apple添加了一個新的庫JavaScriptCore
,用來作JS交互,所以JS與原生OC交互也變得簡單了許多。web
JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
- (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。app
- (void)webViewDidFinishLoad:(UIWebView *)webView { [SVProgressHUD dismiss]; __weak typeof(self) weakSelf = self; JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; context[@"goHisBack"] = ^() { // 後退 // NSArray *args = [JSContext currentArguments]; [weakSelf JSCallOCWithGoHisBack]; }; context[@"Jumpomment"] = ^() { // 跳轉評論 NSArray *args = [JSContext currentArguments]; [weakSelf JSCallOCWithJumpomment:args]; }; context[@"openShare"] = ^() { // 打開分享 NSArray *args = [JSContext currentArguments]; [weakSelf JSCallOCWithOpenShare:args]; }; context[@"showAlert"] = ^() { // 點贊提示 NSArray *args = [JSContext currentArguments]; [weakSelf JSCallOCWithShowAlert:args]; }; } - (void)JSCallOCWithGoHisBack { __weak typeof(self) weakSelf = self; dispatch_async(dispatch_get_main_queue(), ^{ // 返回上一界面 [weakSelf.navigationController popViewControllerAnimated:YES]; }); } - (void)JSCallOCWithJumpomment:(NSArray *)args { __weak typeof(self) weakSelf = self; ZCYCommentDetailViewController *commentDVC = [[ZCYCommentDetailViewController alloc] init]; commentDVC.dataModel = self.dataModel; dispatch_async(dispatch_get_main_queue(), ^{ [weakSelf.navigationController pushViewController:commentDVC animated:YES]; }); } - (void)JSCallOCWithOpenShare:(NSArray *)args { dispatch_async(dispatch_get_main_queue(), ^{ // 打開分享面板 [ZCYShareTool showShareViewWithModel:self.dataModel]; }); } - (void)JSCallOCWithShowAlert:(NSArray *)args { dispatch_async(dispatch_get_main_queue(), ^{ // 點贊提示 [MBProgressHUD showSuccess:[NSString stringWithFormat:@"%@",[args firstObject]]]; }); }
原文連接:http://www.jianshu.com/p/d19689e0ed83dom