2010-07-23 4 views
1

J'essaie d'utiliser le Google API api pour ... bien traduire du texte, mais son comportement étrange. Lorsque ma requête (le texte à traduire) ne contient aucun espace, cela fonctionne bien, mais dès que j'introduis un espace dans la requête, je n'obtiens aucun résultat. Ceci est mon code:je n'arrive pas à comprendre cette chaîne JSON

-(void)translateText:(NSString *)originalText { 

    //Construct request url 
    NSString *urlString = [NSString stringWithFormat:@"http://ajax.googleapis.com/ajax/services/language/translate?q=%@&v=1.0&langpair=en%%7cde", originalText]; 
    NSURL *url = [NSURL URLWithString:urlString]; 

    // Get the contents of the URL as a string, and parse the JSON into Foundation objects 
    NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil]; 

    //Get out the translated text 
    NSDictionary *results = [jsonString JSONValue]; 
    NSString *answer = [[results objectForKey:@"responseData"] objectForKey:@"translatedText"]; 

    self.translatedText = answer; 
} 

Je n'arrive pas à comprendre ce qui se passe. Des idées?

Répondre

1

Vous devez URL encode la Originaltext:

http://mesh.typepad.com/blog/2007/10/url-encoding-wi.html

+0

aaaaah, ouais ça le ferait. Merci beaucoup! Pour toute personne qui lisait, j'ai dû appeler ce message sur mon NSString avant d'en sortir un NSURL: [originalText stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding] – lms

1

Ray Wenderlich a récemment fait un tutorial sur la traduction via Google Translate et JSON sur l'iPhone BTW.

Questions connexes