Google Translate API for iPhone - 中文翻译中的 UTF8 问题
我已经通过以下方式测试了可行的翻译 API 网址:
http://translate.google.com/translate_a/t?client=t&text=%E5%BB%A3%E5%A0%B4&langpair=zh |zh-CN
返回正确结果如下,JSON 格式:
{"sentences":[{"trans":"广场","orig":"广场","translit": "guǎngchǎng"}],"src":"zh-CN"}
但是,当我尝试在XCode中使用这个函数时,我遇到了这个问题...... 这是我的代码:
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);
最初我猜想这是编码问题,所以我也尝试了其他编码(NSISOLatin1StringEncoding),但我得到了错误的答案:{“sentences”:[{“trans”:“ã”,“orig”:“ã”,“translit”: "Tu"}],"src":"zh-CN"}
有谁知道如何解决这个问题吗?非常感谢!
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 *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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否尝试过检查错误对象?如果发生错误,此调用将仅设置错误对象并继续 - 它不会像正常错误那样崩溃/抛出。
在 sendSynchronousRequest 调用之后尝试类似的操作:
如果发生错误,这应该提供更多详细信息。
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:
This should give more details if an error occurred.