2013-03-21 53 views
21

我的iOS應用程序中有.html文件。 HTML文件幾乎沒有帶有onClick方法的div塊。 當我點擊這些塊時,我在web視圖中調用了一些javascript代碼,但我還需要在源代碼中瞭解這些事件。使用UIWebView從HTML代碼調用目標c代碼中的方法

例如,當我點擊web元素和onClick被調用時,我需要調用代碼中的某些方法,例如- (void)didTouchedWebElementWithId

我可以做這個東西。謝謝。

回答

49

要調用的Objective-C的方法在JS:

以下網址可以幫助這樣做

How to invoke Objective C method from Javascript and send back data to Javascript in iOS?

沒有執行的方式,我們通過導航到其他頁面做的解決方法在導航過程中,webview委託會監視導航的前綴並執行我們指定的方法。

sample.html

<html> 
    <head> 
     <script type='text/javascript'> 
      function getText() 
      { 
       return document.getElementById('txtinput').value; 
      } 
      function locationChange() 
      { 
       window.location = 'ios:webToNativeCall'; 
      } 
     </script> 
    </head> 
    <body style='overflow-x:hidden;overflow-y:hidden;'> 
     <h2 style = "font-size:16px;" align='center'>Hi Welcome to Webpage</h2> 
     <br/> 
     <p align='center' style = "font-size:12px;">Please Click the button after entering the text</p> 
     <br/> 
     <center> 
      <input type='text' style='width:90px;height:30px;' id='txtinput'/> 
     </center> 
     <br/> 
     <center> 
      <input type='button' style='width:90px;height:30px;' onclick='locationChange()' value='click me'> 
     </center> 
    </body> 
</html> 

Objective-C代碼當你在HTML頁面中單擊按鈕下面的委託

將發射和導航取消,因爲我們返回NO和相應的方法被調用

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType 
{ 
    if ([[[request URL] absoluteString] hasPrefix:@"ios:"]) { 

     // Call the given selector 
     [self performSelector:@selector(webToNativeCall)];   
     // Cancel the location change 
     return NO; 
    } 
    return YES; 
} 

- (void)webToNativeCall 
{ 
    NSString *returnvalue = [self.webviewForHtml stringByEvaluatingJavaScriptFromString:@"getText()"]; 

    self.valueFromBrowser.text = [NSString stringWithFormat:@"From browser : %@", returnvalue ]; 
} 
+0

小心安全隱患! – Gustav 2015-01-17 14:17:34

+0

你能更詳細地瞭解它嗎? – Vinodh 2015-01-19 10:12:25

+0

假設你的類中有一個名爲getSecretToken的方法。那麼你可以從Javascript中調用它 – Gustav 2015-01-19 12:40:51