2013-03-21 10 views
21

Ho un file .html nella mia app iOS. Il file HTML ha pochi blocchi div con metodi onClick. Quando tocco questi blocchi invoco un codice javascript in visualizzazione Web, ma ho bisogno di conoscere anche questi eventi nel mio codice sorgente.Invoca il metodo nel codice obiettivo c dal codice HTML utilizzando UIWebView

Ad esempio, quando tocco l'elemento web e onClick è chiamato, ho bisogno di invocare qualche metodo nel codice, ad es. - (void)didTouchedWebElementWithId

Posso fare questa roba. Grazie.

risposta

49

di chiamare il metodo di Objective-C in JS:

l'URL di seguito aiuta a farlo

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

Non c'è modo di eseguire, facciamo soluzione per una navigazione ad altra pagina e durante la navigazione, un delegato della webview guarderà per il prefisso della navigazione ed eseguirà il metodo che abbiamo specificato.

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 codice

quando si fa clic sul pulsante nella pagina html il delegato di seguito sarà licenziato e navigazione annullato perché torniamo NO e rispettivo metodo viene chiamato

- (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

Attenzione alle implicazioni sulla sicurezza! – Gustav

+0

puoi esserne più dettagliato? – Vinodh

+0

supponi di avere un metodo chiamato getSecretToken nella tua classe. Quindi potresti chiamarlo da Javascript – Gustav

Problemi correlati