我正试图找出最合适的方法来处理在UIWebView
中加载页面时可能发生的错误。
如果我注意到与网络相关的问题或与服务器相关的问题,我想提醒用户。我找不到要检查的特定错误代码的任何详细信息。这就是我现在拥有的:
NSInteger errorCode = [error code];
NSString* title = nil;
NSString* message = nil;
if (errorCode == NSURLErrorNetworkConnectionLost || errorCode == NSURLErrorNotConnectedToInternet) {
title = @"Error";
message = @"The network connection appears to be offline.";
}
if (errorCode == NSURLErrorTimedOut || errorCode == NSURLErrorBadServerResponse) {
title = @"Error";
message = @"There was an error loading the request. Please try again later.";
}
if (title != nil) {
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
alert.tag = TAG_WEB_ERROR;
[alert show];
}
我是否正在检查正确的错误代码?有没有想过一种更好的方法来检查和处理潜在的错误?
NSURLError.h
中定义了一些错误代码例如NSURLErrorTimedOut
if ([error.domain isEqualToString:NSURLErrorDomain]) {
if(error.code == NSURLErrorTimedOut) {
...
}
}
不确定这是否是UIWebView返回的完整错误代码集。而且没有像NSError列表这样的东西,你需要检查代码和域。
假设您在视图控制器中使用UIWebView,您可以将视图控制器设置为UIWebView的委托,并从UIWebViewDelegate协议实现以下方法
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Error" message:[error localizedDescription] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
alert.tag = TAG_WEB_ERROR;
[alert show];
}
也许没有直接回答您的问题(我在检查正确的错误代码吗?),但Mattt Thompson在NSHipster的NSError
中对NSURLErrorDomain
和CFNetworkErrors
都有一个很好的概述。
该列表在一个格式整齐的表中包含可能的错误代码、错误域和相关原因。