0

我尝试添加一个方法来处理异常,但程序只是崩溃而不是弹出一个 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 的任何想法?

4

1 回答 1

3

查看我在此文件中的错误处理。如果您将 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");
}
于 2009-03-07T18:22:21.593 回答