iOS OC和Javascript互相調用

最近在iOS項目中需要使用到oc與js之間的相互調用,而且要求是實現方式必須與Android中的相同,方便js中統一處理。於是在對第三方庫WebViewJavascriptBridge進行研究之後,仿照Android中的WebView與JS的交互機制,實現了一個,在這裏分享給大家。

首先要說明的是,在iOS中js調用Objective-C的代碼只能通過重定向的形式進行,即js中通過修改iframe的src,或者直接跳轉到一個url,在Objective-C中通過UIWebView的

webView:shouldStartLoadWithRequest:navigationType:方法攔截這個跳轉,然後通過解析跳轉的url獲取js需要調用的方法名和參數。而在Android中,只需要調用WebView的addJavascriptInterface方法,將一個js對象綁定到一個java類,在類中實現相應的函數,當js需要調用java的方法時,只需要直接在js中通過綁定的對象調用相應的函數即可。

顯然Android中js交互的方式要比iOS上方便得多,因此,我們可以在iOS上實現一套與Android相類似的機制。下面先說明一下實現的原理,要在js中直接通過綁定的對象調用相應的函數,那麼就需要在js中添加相應的代碼,但是爲了確保與Android的一致性,js代碼應該在客戶端以注入的形式加入。所以,我們先實現一下需要注入的代碼:

[javascript] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. ;(function() {  
  2.     var messagingIframe,  
  3.         bridge = 'external',  
  4.         CUSTOM_PROTOCOL_SCHEME = 'jscall';  
  5.     
  6.     if (window[bridge]) { return }  
  7.   
  8.     function _createQueueReadyIframe(doc) {  
  9.         messagingIframe = doc.createElement('iframe');  
  10.         messagingIframe.style.display = 'none';  
  11.         doc.documentElement.appendChild(messagingIframe);  
  12.     }  
  13.     window[bridge] = {};  
  14.     var methods = [%@];  
  15.     for (var i=0;i<methods.length;i++){  
  16.         var method = methods[i];  
  17.         var code = "(window[bridge])[method] = function " + method + "() {messagingIframe.src = CUSTOM_PROTOCOL_SCHEME + ':' + arguments.callee.name + ':' + encodeURIComponent(JSON.stringify(arguments));}";  
  18.         eval(code);  
  19.     }  
  20.     
  21.     //創建iframe,必須在創建external之後,否則會出現死循環  
  22.     _createQueueReadyIframe(document);  
  23.     //通知js開始初始化  
  24.     //initReady();  
  25. })();  


在以上代碼中,我們在網頁中添加了一個iframe,使得改變iframe的src時webview可以捕捉到重定向請求,使用這種方式進行重定向,相比直接修改網頁的url要安全得多。同時設置了一個external對象,併爲該對象綁定了若干方法,具體的方法之後會添加,當這兩個方法執行時,會修改iframe的src,並將要調用的方法和參數以url的形式來構造。然後,我們需要在webview完成網頁加載的時候進行注入,實現以下委託:
  1. - (void)webViewDidFinishLoad:(UIWebView *)webView {  
  2.     if (webView != _webView) { return; }  
  3.     //is js insert  
  4.     if (![[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"typeof window.%@ == 'object'", kBridgeName]] isEqualToString:@"true"]) {  
  5.         //get class method dynamically  
  6.         unsigned int methodCount = 0;  
  7.         Method *methods = class_copyMethodList([self class], &methodCount);  
  8.         NSMutableString *methodList = [NSMutableString string];  
  9.         for (int i=0; i<methodCount; i++) {  
  10.             NSString *methodName = [NSString stringWithCString:sel_getName(method_getName(methods[i])) encoding:NSUTF8StringEncoding];  
  11.             [methodList appendString:@"\""];  
  12.             [methodList appendString:[methodName stringByReplacingOccurrencesOfString:@":" withString:@""]];  
  13.             [methodList appendString:@"\","];  
  14.         }  
  15.         if (methodList.length>0) {  
  16.             [methodList deleteCharactersInRange:NSMakeRange(methodList.length-11)];  
  17.         }  
  18.           
  19.         NSBundle *bundle = _resourceBundle ? _resourceBundle : [NSBundle mainBundle];  
  20.         NSString *filePath = [bundle pathForResource:@"WebViewJsBridge" ofType:@"js"];  
  21.         NSString *js = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];  
  22.         [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:js, methodList]];  
  23.     }  
  24.   
  25.     __strong typeof(_webViewDelegate) strongDelegate = _webViewDelegate;  
  26.     if (strongDelegate && [strongDelegate respondsToSelector:@selector(webViewDidFinishLoad:)]) {  
  27.         [strongDelegate webViewDidFinishLoad:webView];  
  28.     }  
  29. }  

該委託對加載完成的網頁進行了js注入,將類中實現的方法添加到了js中。注意,以上代碼在注入前需要判斷是否已經注入,避免重複注入。接下來,我們可以再實現一個webview的委託來攔截重定向事件:

  1. - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {  
  2.     if (webView != _webView) { return YES; }  
  3.     NSURL *url = [request URL];  
  4.     __strong typeof(_webViewDelegate) strongDelegate = _webViewDelegate;  
  5.       
  6.     NSString *requestString = [[request URL] absoluteString];  
  7.     if ([requestString hasPrefix:kCustomProtocolScheme]) {  
  8.         NSArray *components = [[url absoluteString] componentsSeparatedByString:@":"];  
  9.           
  10.         NSString *function = (NSString*)[components objectAtIndex:1];  
  11.         NSString *argsAsString = [(NSString*)[components objectAtIndex:2]  
  12.                                   stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  
  13.         NSData *argsData = [argsAsString dataUsingEncoding:NSUTF8StringEncoding];  
  14.         NSDictionary *argsDic = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:argsData options:kNilOptions error:NULL];  
  15.         //convert js array to objc array  
  16.         NSMutableArray *args = [NSMutableArray array];  
  17.         for (int i=0; i<[argsDic count]; i++) {  
  18.             [args addObject:[argsDic objectForKey:[NSString stringWithFormat:@"%d", i]]];  
  19.         }  
  20.         //ignore warning  
  21. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"  
  22.         SEL selector = NSSelectorFromString([args count]>0?[function stringByAppendingString:@":"]:function);  
  23.         if ([self respondsToSelector:selector]) {  
  24.             [self performSelector:selector withObject:args];  
  25.         }  
  26.         return NO;  
  27.     } else if (strongDelegate && [strongDelegate respondsToSelector:@selector(webView:shouldStartLoadWithRequest:navigationType:)]) {  
  28.         return [strongDelegate webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];  
  29.     } else {  
  30.         return YES;  
  31.     }  
  32. }  

以上代碼中對重定向的url進行了判斷,如果符合我們事先定義的協議,就進行解析,否則就進行跳轉。解析的時候以冒號分隔,取出函數名和參數列表,並調用相應的方法。至此,我們就在iOS中實現了與Android相同的調用機制。

爲了方便大家使用,我將以上代碼封裝成了一個類,具體的使用方法見Demo

需要注意的是:

1. 在實際應用中可能出現js執行順序的問題,如果網頁中的js在注入前先獲取綁定的對象進行保存,是無法獲取到的,因爲這時候待綁定的對象爲空。這就需要網頁中js的初始化在注入之後,因此在上文代碼中有一個initReady方法。

2. 由於performSelector最多隻能包含兩個參數,因此例子中是通過數組來傳遞參數列表的。


如果大家覺得對自己有幫助的話,還希望能幫頂一下,謝謝:)
轉載請註明出處,謝謝!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章