2010-04-20 129 views
1

我已經測試了一個可行的翻譯API網址:谷歌翻譯API爲iPhone UTF8問題,在中國翻譯

http://translate.google.com/translate_a/t?client=t&text=%E5%BB%A3%E5%A0%B4&langpair=zh|zh-CN

,並返回正確的結果是JSON格式如下:

{ 「句子」:[{ 「反式」: 「廣場」, 「原稿」: 「廣場」, 「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),但我得到了錯誤的答案:{「句子」:[{「反式」:「A」,「原稿」:」 ã「,」translit「:」Tu¨¯「}],」src「:」zh-CN「}

有誰知道如何解決這個問題?非常感謝你!

回答

0

您是否嘗試過檢查錯誤對象?如果發生錯誤,該調用將只設置錯誤對象並繼續 - 它不會像正常錯誤那樣崩潰/拋出。

嘗試這樣的sendSynchronousRequest調用後:

if (error != nil) 
{ 
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
    abort(); 
} 

如果發生錯誤,這應該提供更多的細節。