关于iPhone上的HTTP异常处理的问题

时间:2009-03-03 08:53:14

标签: iphone http exception exception-handling connection

我尝试添加一个方法来处理异常,但程序崩溃而不是弹出一个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 个答案:

答案 0 :(得分: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");
}
相关问题