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 & instead of &, " instead of " (double quote), etc so I had to manually decode it.
+ (NSString *) decodeCharacters:(NSString *)string {
NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];
[dict setObject:@"&" forKey:@"&"];
[dict setObject:@"\"" forKey:@"""];
[dict setObject:@"'" forKey:@"'"];
[dict setObject:@"<" forKey:@"<"];
[dict setObject:@">" 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;
}
Wednesday, April 6, 2011
Subscribe to:
Post Comments (Atom)
1 comments:
Thanks for the post..
encode url
Post a Comment