2011-11-10 157 views
0

這是谷歌翻譯解析器。我從api v1切換到api v2(付費),但是我遇到了問題。翻譯是在日誌中完成的,但是responseStatus是0而不是200.您可以查看日誌,翻譯完成。在Google的頁面上,json中應該也會出現在頂部的「200 OK」,但是並沒有出現。想法?Xcode:切換到谷歌API api V2(谷歌翻譯)

-(void)getText:(NSString *)text lan1:(NSString *)lan1 lan2:(NSString *)lan2 { 
translate = [[NSString stringWithString:text] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
lanTranslate = [[NSString stringWithString:lan1] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
lanTranslated = [[NSString stringWithString:lan2] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
[self performTranslation]; 
} 
-(void)performTranslation { 

responseData = [NSMutableData data]; 

NSString *_translation = [NSString stringWithFormat:@"%@&target=%@", lanTranslate,lanTranslated]; 
NSString *translation = [_translation stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 

NSString *url = [NSString stringWithFormat:@"https://www.googleapis.com/language/translate/v2?key=MYKEY&source=%@&q=%@",translation, translate]; 
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]]; 

NSURLConnection *go = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
[go start]; 


} 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
[responseData setLength:0]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
[responseData appendData:data]; 
} 
- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 

NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; 
NSMutableDictionary *JSONDictionary = [responseString JSONValue]; 

NSLog(@"res %@ js%@",responseString, JSONDictionary); 


if (JSONDictionary != nil) 
{ 
    NSDecimalNumber * responseStatus = [JSONDictionary objectForKey:@"responseStatus"]; 
    if ([responseStatus intValue] != 200) { 

     **NSLog(@"responseStatus %i",(int)responseStatus);** 

     return; 
    } 

    NSMutableDictionary *responseDataDict = [JSONDictionary objectForKey:@"responseData"]; 
    if (responseDataDict != nil) { 
     NSString *translatedText = [responseDataDict objectForKey:@"translatedText"]; 
     translated = [NSString stringWithString:translatedText];  
     [viewSuperiore translate:translated]; 

    } 
} 


} 

日誌

res { 
"data": { 
"translations": [ 
{ 
"translatedText": "text to be translated" 
} 
] 
} 
} 
js{ 
data =  { 
    translations =   (
        { 
      translatedText = "text to be translated"; 
     } 
    ); 
}; 
} 

回答

0

HTTP狀態代碼似乎並沒有成爲谷歌翻譯API v2的結果的一部分。

(換句話說,你在上面的代碼爲0,因爲關鍵@「responseStatus」是不存在的JSON有效載荷)

解決方案(爲我的作品): 您應該找回狀態從請求的響應,返回代碼無論是在連接:didReceiveResponse:調用後委託或右sendSynchronousRequest:returningResponse:錯誤:同步請求:

NSInteger的responseStatus = [(NSHTTPURLResponse *)響應的StatusCode];

希望這會有所幫助。