1

只是想知道下面的这段代码......当我关闭我的互联网连接并运行它时,我预计我会在我的控制台日志中得到“连接失败”。谁能解释为什么我不是?谢谢。

NSString *urlString = [NSString stringWithFormat:@"http://www.myurl.com/RSS/feed.xml"];

NSURL *serviceURL = [NSURL URLWithString:urlString];

//Create the request
NSURLRequest *request = [NSURLRequest requestWithURL:serviceURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];

//Create the connection and send the request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];


//Make sure the connection is good
if (connection) {
    //instantiate the responseData structure to store the response
    self.responseData = [NSMutableData data];

}
else {
    NSLog(@"Connection failed");
}
4

2 回答 2

1

您实际上还没有尝试提出请求。 if (connection)不测试请求是否成功,它只测试您是否能够创建表示连接的对象。您仍然需要调用其中一种方法来发出请求。有关详细信息,请参阅文档

于 2012-03-22T13:06:24.570 回答
1

您想检查连接本身是否失败,而不是连接对象的创建,请使用委托,如下所示:

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
        NSLog("Oh noes D=");
}
于 2012-03-22T13:19:30.370 回答