使用 error.code 处理 NSError

Handling NSError with error.code

我正在尝试使用 UIAlertView 处理特定的 NSErrors,但是当调用 webview didFailLoadWithError 时调用了 if 语句中的 none 代码。以下是我的条件陈述:

 - (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。谢谢

问题是你永远不会越过这条线:

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

因此,如果错误代码是 -1009,或 任何 -999,则为时已晚 - 您已经说过 return 并且一切都结束了。后面的代码不会执行。