使用error.code处理NSError

时间:2015-04-27 23:31:36

标签: ios error-handling conditional nserror

我正在尝试使用NSErrors来处理特定UIAlertView,但在调用webview didFailLoadWithError时,if语句中的所有代码都不会被调用。以下是我的条件声明:

 - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
loadFailedBool = YES;
NSLog(@"Error code %ld", (long)[error code]);
if ([error code] != -999) {
    //loading was cancelled and another one initiated. Don't show alert
    return;
}
else if ([error code] == NSURLErrorTimedOut || [error code] == kCFURLErrorTimedOut) {
    //connection timed out
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"Network Connection timed out" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
    alert.tag = 1;
}
else if ([error code] == -1005) {
    //connection lost
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"Network Connection to the host is lost" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
    alert.tag = 1;
}
else if ([error code] == kCFURLErrorNotConnectedToInternet || [error code] == -1009) {
    //no internet connection
    NSLog(@"Error here");
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"Looks like you are not connected to the internet" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
    alert.tag = 1;
}
else if ([error.domain isEqualToString:@"WebKitErrorDomain"] && error.code == 102) {

    return;
  }
}

我的问题是,我如何得到调用的条件,因为日志有时会在没有互联网的情况下打印-1009。感谢

1 个答案:

答案 0 :(得分:2)

问题是你永远不会超越这一行:

if ([error code] != -999) {
    return;
}

因此,如果错误代码为-1009,或任何-999,则为时已晚 - 您已经说过return了整件事情结束了。后面的代码不会执行。