2010-09-18 20 views
13

Tengo NSString y una vista web en mi proyecto (Objective-C para iPhone), he llamado index.html en webView y en su interior he insertado mi secuencia de comandos (javascript).NSString en UIWebview

¿Cómo puedo pasar el NSString como una var en mi script y viceversa?

Esto es example, pero no lo entiendo muy bien.

+0

He agregado UIWebView y UIWebViewDelegate a las etiquetas (en lugar de xcode y html) –

Respuesta

30

Enviar cadena a vista web:

[webView stringByEvaluatingJavaScriptFromString:@"YOUR_JS_CODE_GOES_HERE"]; 

Enviar secuencia de la vista web para Obj-C:

Declarar que implemente el protocolo UIWebViewDelegate (dentro del archivo .h):

@interface MyViewController : UIViewController <UIWebViewDelegate> { 

    // your class members 

} 

// declarations of your properties and methods 

@end 

En Objective-C (dentro del archivo .m):

// right after creating the web view 
webView.delegate = self; 

En Objective-C (dentro del archivo .m) también:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { 
    NSString *url = [[request URL] absoluteString]; 

    static NSString *urlPrefix = @"myApp://"; 

    if ([url hasPrefix:urlPrefix]) { 
     NSString *paramsString = [url substringFromIndex:[urlPrefix length]]; 
     NSArray *paramsArray = [paramsString componentsSeparatedByString:@"&"]; 
     int paramsAmount = [paramsArray count]; 

     for (int i = 0; i < paramsAmount; i++) { 
      NSArray *keyValuePair = [[paramsArray objectAtIndex:i] componentsSeparatedByString:@"="]; 
      NSString *key = [keyValuePair objectAtIndex:0]; 
      NSString *value = nil; 
      if ([keyValuePair count] > 1) { 
       value = [keyValuePair objectAtIndex:1]; 
      } 

      if (key && [key length] > 0) { 
       if (value && [value length] > 0) { 
        if ([key isEqualToString:@"param"]) { 
         // Use the index... 
        } 
       } 
      } 
     } 

     return NO; 
    } 
    else { 
     return YES; 
    } 
} 

Dentro JS:

location.href = 'myApp://param=10'; 
+3

y al revés? :-) – MJB

0

Al pasar un NSString en un UIWebView (para su uso como una cadena de JavaScript) debe asegurarse de evitar las líneas nuevas, así como las comillas simples/dobles:

NSString *html = @"<div id='my-div'>Hello there</div>"; 

html = [html stringByReplacingOccurrencesOfString:@"\'" withString:@"\\\'"]; 
html = [html stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""]; 
html = [html stringByReplacingOccurrencesOfString:@"\n" withString:@"\\n"]; 
html = [html stringByReplacingOccurrencesOfString:@"\r" withString:@""]; 

NSString *javaScript = [NSString stringWithFormat:@"injectSomeHtml('%@');", html]; 
[_webView stringByEvaluatingJavaScriptFromString:javaScript]; 

el proceso de ever está bien descrito por @ Michael-Kessler