怎么可能connectionDidFinishLoading:运行,如果在服务器上找不到文件?

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

这是奇怪的; 我有这样的asynchronous连接:

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也在运行。 为什么? 我不希望它已经加载任何东西,而是导致错误和警报视图。

这些方法起初看起来很清楚,但是在这里肯定会发生一些事情,我不了解asynchronous连接。

它完成加载。 事实上,它完成了一个HTTP错误是没有关系的。

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