Вопрос об обработке HTTP-исключений на iPhone - PullRequest
0 голосов
/ 03 марта 2009

Я пытаюсь добавить метод для обработки исключений, но программа просто аварийно завершает работу вместо всплывающего окна AlertView.

1) Я установил соединение:

-(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) Я добавляю метод для получения данных и преобразования их в строку:

- (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) Я добавляю метод обработки исключений:


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

После того, как я изменил strURL на неправильный URL, программа просто вылетает. Есть идеи, почему AlertView не появляется?

1 Ответ

3 голосов
/ 07 марта 2009

Проверьте обработку ошибок , которую я получил в этом файле . Если вы установите недействительный URL, он (в моем примере) вернется с хорошим сообщением об ошибке диалога. Я просто попробовал это, чтобы быть уверенным.

Соответствующий код в связанном файле:

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