views:

51

answers:

2

I'm trying to use the google translate api's to... well translate some text, but its behaving strangely. When my query (the text to be translated) contains no spaces, it works fine, however as soon as I introduce a space into the query, i get no results back. This is my code:

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

I can't figure out what the hell is happening. Any ideas?

+1  A: 

You need to URL encode the originalText:

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

Lou Franco
aaaaah, yeah that would do it. thx a lot!for anyone else reading, i had to call this message on my NSString before making an NSURL out of it: [originalText stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]
codenoob
A: 

Ray Wenderlich recently did a tutorial on translating via Google Translate and JSON on the iPhone BTW.

Joost Schuur