2010-05-22 54 views
0

我有這樣的代碼從Objective-C發送消息並獲取返回值?

NSString *tr = [self sendUrl:@"http://google.com/"]; 

但出於某種原因「TR」仍將執行完成後爲零。我究竟做錯了什麼?

sendUrl:

- (NSString *)sendUrl:(NSString *) uri { 

NSLog(@"Requesting URI 1 ..."); 

// Prepare URL request to download statuses from Twitter 
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:uri]]; 

NSLog(@"Requesting URI 2 ..."); 

// Perform request and get JSON back as a NSData object 
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 

NSLog(@"Requesting URI 3 ..."); 

// Get JSON as a NSString from NSData response 
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; 

NSLog(@"Requesting URI 4 ..."); 

return json_string; 
} 
+0

sendUrl的實現是什麼:? – BoltClock 2010-05-22 15:30:25

+0

看起來很好。你是否100%確定你的sendUrl函數正在工作 - 分步執行代碼並向你自己證明。 – blissapp 2010-05-22 15:30:25

+0

sendUrl不是內置方法,是不是?我無法搜索它?你可以給我鏈接到方法描述/文檔。沒有這些,我不知道會發生什麼 – vodkhang 2010-05-22 15:31:32

回答

3

你絕對肯定response不是零?如果您的請求,以谷歌或其他地方失敗,響應將被設置爲nil和錯誤會包含一些信息,幫助您診斷錯誤,以便改變

NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 

NSError* error = nil; 
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error]; 
if (response == nil) 
{ 
    NSLog(@"request failed with error %@", error); 
    // any other error handling 
} 

接下來的事情。 HTTP消息的默認編碼是ISO-8859-1,而不是UTF-8。根據Apple的文檔,如果編碼錯誤,-initWithData將返回nil。你可能是想要NSISOLatin1StringEncoding。我說「可能」,因爲HTTP有一種機制來告訴你它使用了什麼字符編碼。我認爲它是Content-Transfer-Encoding的頭文件,但我建議你通過HTTP HTTP來確認。

最後如果json_string不是零,它會泄漏。因爲你用alloc獲得它,所以你擁有它,這意味着你需要在從sendURL返回它之前自動釋放它:最後一點不是你的問題的原因,它是你的代碼中的一個單獨的錯誤。

相關問題