Wednesday, April 6, 2011

Encode URL and Decode Google Translate's Response in Objective C

I've been working on a project that needs to get a translation from google translate web service. There are some codes in google code that can help you doing this. However, I found some problems regarding string encoding.

I used to encode the string with NSUTF8StringEncoding, but it doesn't encode character & into %26 or + into %2B so I had to encode it manually.

NSString* urlEncodedText = [text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
urlEncodedText = [CommonUtil encodeCharacters:urlEncodedText];

+ (NSString*) encodeCharacters:(NSString*) string {
NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];
[dict setObject:@"%26" forKey:@"&"];
[dict setObject:@"%2B" forKey:@"+"];

NSArray* keys = [dict allKeys];
for (int i = 0; i < [keys count]; i++) {
NSString* key = [keys objectAtIndex:i];
string = [string stringByReplacingOccurrencesOfString:key withString:[dict objectForKey:key]];
}

return string;
}

The same thing happens when I get the translation. I get &amp; instead of &, &quot; instead of " (double quote), etc so I had to manually decode it.

+ (NSString *) decodeCharacters:(NSString *)string {
NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];
[dict setObject:@"&" forKey:@"&amp;"];
[dict setObject:@"\"" forKey:@"
&quot;"];
[dict setObject:@"'" forKey:@"
&#39;"];
[dict setObject:@"<" forKey:@"
&lt;"];
[dict setObject:@">" forKey:@"
&gt;"];

NSArray* keys = [dict allKeys];
for (int i = 0; i < [keys count]; i++) {
NSString* key = [keys objectAtIndex:i];
string = [string stringByReplacingOccurrencesOfString:key withString:[dict objectForKey:key]];
}

return string;
}
 

©2009 Stay the Same | by TNB