Google Translate API for iPhone - UTF8 problem in Chinese Translation
- by Sky Chen
I've tested a workable translation API url by:
http://translate.google.com/translate_a/t?client=t&text=%E5%BB%A3%E5%A0%B4&langpair=zh|zh-CN
And it returns the correct result as the following which is in JSON format:
{"sentences":[{"trans":"??","orig":"??","translit":"Guangchang"}],"src":"zh-CN"}
However, when I try to use this function in XCode, I experienced this problem ...
Here is my code:
NSData *data;
NSString *urlPath = [NSString stringWithFormat:@"/translate_a/t?client=t&text=%@&langpair=zh|zh-CN",qText];
NSURL *url = [[NSURL alloc] initWithScheme:@"http"
host:@"translate.google.com"
path:urlPath];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:@"GET"];
NSURLResponse *response;
NSError *error;
data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; //Problem's here. It returns nil.
NSLog(result);
Initially I guessed it's encoding problem so I tried other encoding as well (NSISOLatin1StringEncoding) , but I got wrong answer: {"sentences":[{"trans":"ã ","orig":"ã ","translit":"Tu¨¯ "}],"src":"zh-CN"}
Does anyone know how to solve this problem? Thank you very much!