nsurlconnecion doesn't return nil even if network is down
Quite new to network programming and espacially objective-c networking...
Even if I shut down the 开发者_运维知识库network interface on my computer, or sets my iPhone in flught mode, NSURLConnection won't return nil with the unpleasent surprise that the application dies.I conform to NSURLConnection protocol with all correct callback methods...
So how would you handle the case where the client has no internet connection?
Code snippet where I post login data to a server:
-(void)Login {
...
NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:post delegate:self];
if (theConnection==nil) {
//Here I want to show an alert but this case never happens....
}
else {
receivedData=[[NSMutableData data] retain];
}
}
...
//This callback is called correctly but no alert shows up and after this method app dies.
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[connection release];
[receivedData release];
[self setLoggedIn:NO];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
message:[error localizedDescription]
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles: nil];
[alert show];
[alert release];
}
Your app probably crashes because you are releasing the connection object even though you don't own it. Remove [connection release];
from the delegate method.
精彩评论