Google Translate API for iPhone - UTF8 problem in Chinese Translation
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":"Guǎngchǎng"}],"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 *respon开发者_StackOverflowse;
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!
Have you tried checking the error object? If an error occurs, this call will just set the error object and continue - it won't crash/throw like a normal error.
Try something like this after the sendSynchronousRequest call:
if (error != nil)
{
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
This should give more details if an error occurred.
精彩评论