2009-03-03 6 views
0

Я пытаюсь добавить метод обработки исключения, но программа просто сработает, а не всплывает AlertView.Вопрос об обработке исключений HTTP на iPhone

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

- (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 не появляется?

+0

Вы пробовали работает по программе с отладчиком? Вызывается ли ваш 'didFailWithError'? Какая ошибка? –

+0

Нет, метод 'didFailWithError' не вызывался. Я использую неправильный URL для подключения, поэтому я не понимаю, почему он не был вызван. –

ответ

3

Отъезд error handling that I've got in this file. Если вы установили URL-адрес неверного 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"); 
} 
+0

Спасибо. Сейчас я нахожу проблему. Я должен подождать 60 секунд, чтобы увидеть предупреждение, когда я установил интервал тайм-аута 60 секунд. –