views:

727

answers:

1

I try to add a method to handle exception, but the program just crashes instead of pop up an AlertView.

1) I set up the connection:

-(void)connect:(NSString *)strURL
{
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:strURL]
                    cachePolicy:NSURLRequestUseProtocolCachePolicy   
                  timeoutInterval:60.0];

    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if (theConnection) 
    {
     // receivedData is declared as a method instance elsewhere
     receivedData = [[NSMutableData data] retain];
    } 
    else 
    { 
     // inform the user that the download could not be made
    }

}

2)I add method to receive data and conver it to string:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // append the new data to the receivedData
    // receivedData is declared as a method instance elsewhere
    [receivedData appendData:data];
    ReturnStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
}

3)I add exception handle method:


-(void) connection:(NSURLConnection *)connection didFailWithError: (NSError *)error {

    UIAlertView *errorAlert = [[UIAlertView alloc]
             initWithTitle: [error localizedDescription]
             message: [error localizedFailureReason]
             delegate:self
             cancelButtonTitle:@"OK"
             otherButtonTitles:nil];
    [errorAlert show];
}   

After I change the strURL to a wrong url, the program just crashes. Any ideas why the AlertView doesn't pop up?

+2  A: 

Check out the error handling that I've got in this file. If you set the URL to an invalid URL, it does (in my example) come back with a nice dialog error message. I just tried it to be sure.

Relevant code in the linked file is:

-(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");
}
Matthew McCullough
Thanks. I find the problem now. I should wait 60 seconds to see the alert as I set the timeout interval 60 sec.
iPhoney