views:

950

answers:

1

I want to write some code to handle exceptions when HTTP connection fails. I use the following codes:

-(void) connection:(NSURLConnection *)connection
  didFailWithError: (NSError *)error {
    UIAlertView *errorAlert = [[UIAlertView alloc]
        initWithTitle: [error localizedDescription]
        message: [error localizedFailureReason]
        delegate:nil
        cancelButtonTitle:@"OK"
        otherButtonTitles:nil];
    [errorAlert show];
    [errorAlert release];
    [activityIndicator stopAnimating];
    NSLog (@"Connection Failed with Error");
}

But the programme just crashes when the connection fails. How to let the alert pop up without program crash?

+2  A: 

Nothing is obviously wrong with your code, you will need to supply more information.

Make sure you have a breakpoint on objc_exception_throw and then run the program under the debugger. Then you can determine on what line the exception is thrown.

A wild guess, but perhaps [error localizedDescription] or [error localizedFailureReason] is returning nil.

benzado
The method 'didFailWithError' didn't even get called when I use a wrong url. Any ideas why this happens?
iPhoney
Maybe it is not failing? If you get a response from the server, I *think* that counts as success, even if it is a 404 Not Found response.
benzado
Not faliling with wrong url? Then how to add a warning for wrong url? I mean which method should I use?
iPhoney
Is your didSucceed code being called? If so, check the HTTP response code, there's a method on the NSURLResponse object.
benzado
I find my problem now. I should wait for 60 seconds of timeout interval to see the alert. Thanks indeed for your help.
iPhoney