我的iPhone应用程序或Xcode存在问题。 我目前正在尝试将我从Google Translate获得的字符串转换为支持西里尔字母的字符串格式。到目前为止,我尝试了很多String Encodings,但它们似乎都没有正常工作。
到目前为止,这是我的代码:
NSString *word = @"hello";
NSString *urlPath = [NSString stringWithFormat:@"/translate_a/t?client=t&text=%@&langpair=en|ru",word];
NSURL *url = [[NSURL alloc] initWithScheme:@"http" host:@"translate.google.com" path:urlPath];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@"GET"];
NSURLResponse *response;
NSError *error;
NSData *data;
data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *result = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"%@", result);
这是控制台上的结果:
[
[
[
"ÐÒÉ×ÅÔ",
"hello",
"privet",
""
]
],
[
[
"verb",
[
"ÚÄÏÒÏ×ÁÔØÓÑ",
"Ú×ÁÔØ",
"ÏËÌÉËÁÔØ"
],
[
[
"ÚÄÏÒÏ×ÁÔØÓÑ",
[
"greet",
"hello",
"salute",
"hullo",
"hallo",
"halloa"
],
,
0.0050860695
],
[
"Ú×ÁÔØ",
[
"call",
"invite",
"shout",
"hail",
"hallo",
"hello"
],
,
2.7109536e-05
],
[
"ÏËÌÉËÁÔØ",
[
"hail",
"holler",
"call",
"challenge",
"speak",
"hello"
],
,
2.7109536e-05
]
],
"hello",
2
],
[
"noun",
[
"ÐÒÉ×ÅÔÓÔ×ÉÅ",
"ÐÒÉ×ÅÔÓÔ×ÅÎÎÙÊ ×ÏÚÇÌÁÓ",
"×ÏÚÇÌÁÓ ÕÄÉ×ÌÅÎÉÑ"
],
[
[
"ÐÒÉ×ÅÔÓÔ×ÉÅ",
[
"greeting",
"welcome",
"salute",
"hail",
"salutation",
"hello"
],
,
0.0014801305
],
[
"ÐÒÉ×ÅÔÓÔ×ÅÎÎÙÊ ×ÏÚÇÌÁÓ",
[
"hallo",
"halloa",
"viva",
"hello"
],
,
2.7536449e-05
],
[
"×ÏÚÇÌÁÓ ÕÄÉ×ÌÅÎÉÑ",
[
"hallo",
"halloa",
"hello"
],
,
2.7109536e-05
]
],
"hello",
1
]
],
"en",
,
[
[
"ÐÒÉ×ÅÔ",
[
1
],
true,
false,
1000,
0,
1,
0
]
],
[
[
"hello",
1,
[
[
"ÐÒÉ×ÅÔ",
1000,
true,
false
],
[
"úÄÒÁ×ÓÔ×ÕÊÔÅ",
0,
true,
false
],
[
"Hello",
0,
true,
false
],
[
"úÄÒÁ×ÓÔ×ÕÊ",
0,
true,
false
],
[
"ÈÅÌÌÏ",
0,
true,
false
]
],
[
[
0,
5
]
],
"hello"
]
],
,
[
,
"Hello!",
[
10
],
,
true
],
[
],
2
]
所以我希望你能解决我的问题。我希望字符串是“привет”而不是“ÐÒÉ×ÅÔ”。 当我尝试将数据编码为其他格式时,我的字符串通常会得到“(null)”结果,例如NSUTF8StringEncoding。
答案 0 :(得分:2)
“translate.google.com”使用以下参数返回UTF-8:
NSString *urlPath = [NSString stringWithFormat:@"/translate_a/t?client=t&text=%@&langpair=en|ru&ie=UTF-8&oe=UTF-8",word];
然后
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
应该有用。
答案 1 :(得分:0)
对您获得的数据而不是initWithData:encoding:
调用此方法:
- (NSString*)decodeKOI8R:(NSData*)dataToDecode {
CFStringRef aCFString = CFStringCreateWithCString(NULL, [dataToDecode bytes], kCFStringEncodingKOI8_R);
NSString *decodedString = (__bridge NSString*)aCFString;
return decodedString;
}