【问题标题】:Question about HTTP exception handling on iPhone关于 iPhone 上 HTTP 异常处理的问题
【发布时间】:2010-10-10 23:22:43
【问题描述】:

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

【问题讨论】:

  • 你试过用调试器运行程序吗?你的didFailWithError 被叫到了吗?错误是什么?
  • 不,方法 'didFailWithError' 没有被调用。我使用错误的 url 连接所以我不明白为什么没有调用它。

标签: iphone http exception exception-handling connection


【解决方案1】:

查看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");
}

【讨论】:

  • 谢谢。我现在发现问题了。我应该等待 60 秒才能看到警报,因为我将超时间隔设置为 60 秒。
猜你喜欢
  • 2011-09-25
  • 2016-06-27
  • 2010-09-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多