2010-01-11 112 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]; 

    } 
}