2010-01-11 61 views
27

我在網上找到了一個教程,它使用了從iPhone OS 3.0開始不贊成使用的stringWithContentsOfURL命令。但是我無法找到我要使用的內容,以及如何實現它。什麼是目標C的「stringWithContentsOfURL」替代?

以下是圍繞stringWithContentsOfURL行的代碼,以備您需要時參考。

NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv", 
    [addressField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]]; 
NSArray *listItems = [locationString componentsSeparatedByString:@","]; 

謝謝。

回答

29

它已被替換爲stringWithContentsOfURL:encoding:error:stringWithContentsOfURL:usedEncoding:error:

81

由於格雷格,但這裏所有其他初學者是一個例子

NSError* error = nil; 
NSString* text = [NSString stringWithContentsOfURL:TheUrl encoding:NSASCIIStringEncoding error:&error]; 
if(text) 
{ 
    NSLog(@"Text=%@", text); 
} 
else 
{ 
    NSLog(@"Error = %@", error); 
} 
+0

嗨,如果我沒有錯_text_不會_FALSE_或_NIL_即使你的服務器返回一個內部錯誤或類似的東西?這個錯誤更多是關於編碼錯誤? 蘋果是真正嚴格處理連接錯誤,所以我的問題是什麼_stringWithContentsOfURL:encoding:error:_方法,當你不能處理reall「不可用」錯誤?謝謝。 L – luigi7up 2011-05-06 08:34:23

+0

@ luigi7up:我想你說得對。如果存在導致沒有捕獲到返回數據的錯誤(服務器連接錯誤,編碼錯誤),則返回nil。如果發生404錯誤,則會返回一些文本(404錯誤頁面),並且錯誤應該包含錯誤。我不確定這是一個像這樣的同步連接會發生什麼,但這是異步連接的行爲。 – Oliver 2011-08-26 08:52:55

+0

這是否不會爲其他人帶來不兼容的指針類型警告?只有我嗎? – Danny 2014-03-06 22:45:05

1

下面的代碼將刪除你的警告消息........任何問題,請讓莫知道。

- (void) connectedToNetwork 
{ 
    BOOL aflag = ([NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.co.in/"] encoding:NSASCIIStringEncoding error:nil]!=NULL)?YES:NO; 
    if (!aflag) { 
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"Sorry!....You are not connected to network " 
           delegate:self cancelButtonTitle:@"Exit" otherButtonTitles:nil]; 
     [alert show]; 
     [alert release]; 

    } 
}