先用
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
判断一下当前的链接。
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if ((([httpResponse statusCode]/100) == 2)) {
// self.earthquakeData = [NSMutableData data];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[ webView loadRequest:[ NSURLRequest requestWithURL: myUrl ]];
webView.delegate = self;
} else {
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:
NSLocalizedString(@"HTTP Error",
@"Error message displayed when receving a connection error.")
forKey:NSLocalizedDescriptionKey];
NSError *error = [NSError errorWithDomain:@"HTTP" code:[httpResponse statusCode] userInfo:userInfo];
if ([error code] == 404) {
NSLog(@"网络图片不存在");
webView.hidden = YES; //隐藏webView或者用本地默认图片代替
}
}
}
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
判断一下当前的链接。
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if ((([httpResponse statusCode]/100) == 2)) {
// self.earthquakeData = [NSMutableData data];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[ webView loadRequest:[ NSURLRequest requestWithURL: myUrl ]];
webView.delegate = self;
} else {
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:
NSLocalizedString(@"HTTP Error",
@"Error message displayed when receving a connection error.")
forKey:NSLocalizedDescriptionKey];
NSError *error = [NSError errorWithDomain:@"HTTP" code:[httpResponse statusCode] userInfo:userInfo];
if ([error code] == 404) {
NSLog(@"网络图片不存在");
webView.hidden = YES; //隐藏webView或者用本地默认图片代替
}
}
}
本文详细介绍了如何使用Objective-C处理HTTP错误,并在遇到连接错误时进行相应的操作,包括加载请求、设置网络活动指示器可见性和显示错误信息。重点讨论了在不同HTTP状态码下如何响应和处理错误,如404错误时隐藏WebView或使用本地默认图片。
5万+

被折叠的 条评论
为什么被折叠?



