2010-09-18 9 views
13

J'ai un NSString et un webView dans mon projet (Objective-C pour iPhone), j'ai appelé index.html dans webView et à l'intérieur j'ai inséré mon script (javascript).NSString dans UIWebview

Comment puis-je passer le NSString comme var dans mon script et viceversa?

Ceci est un example, mais je ne le comprends pas très bien.

+0

J'ai ajouté UIWebView et UIWebViewDelegate aux balises (au lieu de xcode et html) –

Répondre

30

Envoyer chaîne à l'affichage Web:

[webView stringByEvaluatingJavaScriptFromString:@"YOUR_JS_CODE_GOES_HERE"]; 

chaîne d'envoi de vue Web pour Obj-C:

Declare que vous mettre en œuvre le protocole UIWebViewDelegate (dans le fichier .h):

@interface MyViewController : UIViewController <UIWebViewDelegate> { 

    // your class members 

} 

// declarations of your properties and methods 

@end 

en Objective-C (à l'intérieur du fichier .m):

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

Dans Objective-C (à l'intérieur du fichier .m) aussi:

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

intérieur JS:

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

et l'inverse? :-) – MJB

0

Lors du passage d'un NSString dans un UIWebView (pour une utilisation en tant que chaîne javascript) vous devez vous assurer d'éviter les sauts de ligne ainsi que les guillemets simples ou doubles:

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]; 

processus d'everse est bien décrit par @ Michael-Kessler