A colossal Dreamer: GR鐵塔-天生我材

[아이폰:오브젝티브C] UIWebView와 APP간의 통신(communication) 본문

Development/아이폰

[아이폰:오브젝티브C] UIWebView와 APP간의 통신(communication)

江多林 2010. 3. 3. 08:54


copyright www.irontop.com All rights reserved.

This Example show to you that communication with iPhone App, iPhone UIWebView each other
There is two ways for commucation.
One is the [webView:shouldStartLoadWithRequest:navigationType:] UIWebViewDelegate
The other is the [stringByEvaluatingJavaScriptFromString:] WebView

You can use "shouldStartLoadWithRequest" to commucate UIWebView 2 APP
You can use "stringByEvaluatingJavaScriptFromString" to commucate APP 2 UIWebView

유관업체에서 앱과 웹뷰간의 통신 예제를 작성해달라고 해서.
간단히 만들어 보았다.

웹뷰에는 자바스크립트의 머리를 깎아줄 수 있는 api를 제공하기 때문에(eval)
자바스크립트를 잘 이해하고 있다면, 팝업을 포함하여 거의 모든 기능을 훼이크로 구현이 가능하다.

아래는 주요 코드 부분이다.

APP에서 WebView로 값을 보내는 부분

 71 - (IBAction)toWeb:(id)sender {
 72     NSString *strScript = [NSString stringWithFormat:
 73                            @"var fromApp = document.getElementById('fromApp');\
 74                            fromApp.value = '%@';", self.txtToWebView.text];
 75     [webView stringByEvaluatingJavaScriptFromString:strScript];
 76 }


input 요소를 id로 찾아서 값을 세팅하는 자바스크립트를 생성한 후에
webView에 밀어 넣고 있다.

WebView로부터 APP로 보내지는 값을 획득하는 부분
 83 - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
 84     
 85     NSString *strUrl = [[request URL] absoluteString];
 86     if ([strUrl hasPrefix:@"toAPP://"]) {
 87         NSString *strRequest = [[strUrl componentsSeparatedByString:@"://"] objectAtIndex:1];
 88         NSArray *arrRequest = [strRequest componentsSeparatedByString:@"?"];
 89         NSString *strCmd = [arrRequest objectAtIndex:0];
 90
 91         if (YES == [@"toAppCmd" isEqualToString:strCmd]) {
 92             // code to set Your Application communication
 93             self.txtFromWebView.text = [arrRequest objectAtIndex:1];
 94         }
 95         
 96         // toApp protocol do not StartLoad
 97         return NO;
 98     }
 99     
100     // other protocol do StartLoad
101     return YES;
102 }


form GET Action을 사용하였고,
action-url을 "toApp://toAppCmd?toApp=abc" 형식이 되도록 하였다.
즉, 로드할 url을 가로채서 "toAPP" 로 시작하는 경우에는 NO 를 리턴하여 실제로 로드되지 않도록 하고,
url을 파싱하여 toApp 의 값을 획득하도록 하였다.
여기서 strCmd 를 명령으로 사용하는 예제이므로 toAppCmd 를 다른 값으로 바꾸고,
구분하여 처리하는 것으로 처리할 종류(명령)을 구분할 수 있는 구조로 확장도 가능하다.

자세하는 것은 첨부된 예제 파일을 참조하자.~~