最近準備把以前用JS與原生相互調用功能整理下。順便搜索整理了一下JS 與OC 交互的方式,目前我已知的JS 與 OC 交互的處理方式:html
1.在JS 中作一次URL跳轉,而後在OC中攔截跳轉git
2.利用WKWebView 的MessageHandlergithub
3.利用系統庫JavaScriptCore,來作相互調用(iOS 7推出的)web
4.利用第三方庫WebViewJavascriptBridgejson
5.利用第三方庫EasyJSWebView(已不更新)網絡
6.利用第三方cordova庫,之前叫PhoneGapapp
7.利用第三方DSBridge,值得推薦.(博客裏整理的有,能夠去看看)dom
8.當下火熱的React Native(還沒整理)async
在這裏感謝Haley-Wong大神提供資源.測試
今天就詳細的介紹一下使用UIWebView攔截URL 的方式來實現JS與OC 的交互:
加載本地HTML的目的是便於本身寫JS調用作測試,最終確定仍是加載網絡HTML
self.webView = [[UIWebView alloc] initWithFrame:self.view.frame]; self.webView.delegate = self; NSURL *htmlURL = [[NSBundle mainBundle] URLForResource:@"index.html" withExtension:nil]; // NSURL *htmlURL = [NSURL URLWithString:@"http://www.baidu.com"]; NSURLRequest *request = [NSURLRequest requestWithURL:htmlURL]; // 若是不想要webView 的回彈效果 self.webView.scrollView.bounces = NO; // UIWebView 滾動的比較慢,這裏設置爲正常速度 self.webView.scrollView.decelerationRate = UIScrollViewDecelerationRateNormal; [self.webView loadRequest:request]; [self.view addSubview:self.webView];
本地的HTML裏,我定義了幾個按鈕,來觸發調用原生的方法,而後再將執行結果回調到js 裏
<input type="button" value="掃一掃" onclick="scanClick()" /> <input type="button" value="獲取定位" onclick="locationClick()" /> <input type="button" value="修改背景色" onclick="colorClick()" /> <input type="button" value="分享" onclick="shareClick()" /> <input type="button" value="支付" onclick="payClick()" /> <input type="button" value="搖一搖" onclick="shake()" /> <input type="button" value="返回" onclick="goBack()" /> // js 就列幾個比較有表明性的functions: 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 asyncAlert(content) { setTimeout(function(){ alert(content); },1); } function locationClick() { loadURL("haleyAction://getLocation"); } function setLocation(location) { asyncAlert(location); document.getElementById("returnValue").value = location; }
UIWebView 有一個代理方法,能夠攔截到每個連接的Request。return YES,webView 就會加載這個連接;return NO,webView 就不會加載這個鏈接。咱們就在這個攔截的代理方法中處理本身的URL。
這是個人示例代碼:
#pragma mark - UIWebViewDelegate - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSURL *URL = request.URL; NSString *scheme = [URL scheme]; if ([scheme isEqualToString:@"haleyaction"]) { [self handleCustomAction:URL]; return NO; } return YES; }
這裏經過scheme,來攔截掉自定義的URL 就很是容易了,若是不一樣的方法使用不一樣的scheme,那麼判斷起來就很是的麻煩。
而後,看看個人處理鏈接的方法:
#pragma mark - private method - (void)handleCustomAction:(NSURL *)URL { NSString *host = [URL host]; if ([host isEqualToString:@"scanClick"]) { NSLog(@"掃一掃"); } else if ([host isEqualToString:@"shareClick"]) { [self share:URL]; } else if ([host isEqualToString:@"getLocation"]) { [self getLocation]; } else if ([host isEqualToString:@"setColor"]) { [self changeBGColor:URL]; } else if ([host isEqualToString:@"payAction"]) { [self payAction:URL]; } else if ([host isEqualToString:@"shake"]) { [self shakeAction]; } else if ([host isEqualToString:@"goBack"]) { [self goBack]; } }
順便看一下如何將結果回調到JS中:
- (void)getLocation { // 獲取位置信息
// 將結果返回給js NSString *jsStr = [NSString stringWithFormat:@"setLocation('%@')",@"廣東省深圳市"]; [self.webView stringByEvaluatingJavaScriptFromString:jsStr]; }
固然,有時候咱們在JS中調用OC 方法的時候,也須要傳參數到OC 中,怎麼傳呢?
就像一個get 請求同樣,把參數放在後面:
function shareClick() { loadURL("haleyAction://shareClick?title=測試分享的標題&content=測試分享的內容&url=http://www.baidu.com"); }
那麼若是獲取到這些參數呢?
全部的參數都在URL的query中,先經過&
將字符串拆分,在經過=
把參數拆分紅key 和實際的值。下面有示例代碼:
- (void)share:(NSURL *)URL { 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]]; } } NSString *title = [tempDic objectForKey:@"title"]; NSString *content = [tempDic objectForKey:@"content"]; NSString *url = [tempDic objectForKey:@"url"]; // 在這裏執行分享的操做 // 將分享結果返回給js NSString *jsStr = [NSString stringWithFormat:@"shareResult('%@','%@','%@')",title,content,url]; [self.webView stringByEvaluatingJavaScriptFromString:jsStr]; }
關於將OC 執行結果返回給JS 須要注意的是:
若是回調執行的JS 方法帶參數,而參數不是字符串時,不要加單引號
,不然可能致使調用JS 方法失敗。好比我這樣的:
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userProfile options:NSJSONWritingPrettyPrinted error:nil]; NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; NSString *jsStr = [NSString stringWithFormat:@"loginResult('%@',%@)",type, jsonStr]; [_webView stringByEvaluatingJavaScriptFromString:jsStr];
若是第二個參數用單引號包起來,就會致使JS端的loginResult不會調用。
另外,利用[webView stringByEvaluatingJavaScriptFromString:@"var arr = [3, 4, 'abc'];"];
,能夠往HMTL的JS環境中插入全局變量、JS方法等。