How could connectionDidFinishLoading: run if no fi

2019-09-04 13:06发布

问题:

Possible Duplicate:
Testing use of NSURLConnection with HTTP response error statuses

This is bizarre; I have an async connection like so:

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];
}

Then I have a bunch of standard delegate methods:

-(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.");

}

The NSLog there at the end is running, even if the file is not on the server. Why? I would not expect it to have loaded anything, and instead resulted in an error and an alert view.

These methods seem clear at first, but there must be something going on here that I'm not getting about the async connection.

回答1:

It DID finish loading. The fact that it finished with an HTTP error is beside the point.

The NSHTTPResponse object you got in didReceiveResponse will have a .responseCode property with the 404 in it.