0

可能重复:
测试使用带有 HTTP 响应错误状态的 NSURLConnection

这很奇怪;我有一个像这样的异步连接:

NSString *url=[NSString stringWithFormat:@"http://www.whatever.com/file"];

NSURL *url2=[NSURL URLWithString:url];
NSURLRequest *req=[[NSURLRequest alloc] initWithURL:url2];
NSURLConnection*con=[[NSURLConnection alloc] initWithRequest:req delegate:self];
[req release];

if(con){
    NSMutableData *data=[[NSMutableData alloc] init];
    self.receivedData=data;
    [data release];
}
else {
    UIAlertView*alert=[[UIAlertView alloc] initWithTitle:@"Error!" message:@"Unable to connect to server." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [alert release];
}

然后我有一堆标准的委托方法:

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

}

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

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
[connection release];
self.receivedData=nil;

UIAlertView*alert=[[UIAlertView alloc] initWithTitle:@"This app requires Internet" message:[NSString stringWithFormat: @"Connection failed.\n Please exit and check your\nInternet access."] delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];

[alert show];
[alert release];

}

-(void) connectionDidFinishLoading:(NSURLConnection *)connection{
NSString *payload=[[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
self.downloaded=nil;
self.downloaded=payload;
[payload release];
[connection release];
self.receivedData=nil;

NSLog(@"This will display if connectionDidFinishLoading runs.");

}

最后的 NSLog 正在运行,即使该文件不在服务器上。为什么?我不希望它加载任何东西,而是导致错误和警报视图。

这些方法一开始看起来很清楚,但这里肯定发生了一些我没有了解异步连接的事情。

4

1 回答 1

2

它确实完成了加载。它以 HTTP 错误结束的事实是无关紧要的。

您在 didReceiveResponse 中获得的 NSHTTPResponse 对象将具有一个.responseCode包含 404 的属性。

于 2011-07-11T17:24:39.313 回答