UIWebView didFailWithError is not responding for 404 errors
I am implementing an application that which is having a UIWebView. My problem is I need to display an alert when it fails to load the webv开发者_JAVA百科iew with URL. It is working fine for 1001 and 1009 type errors, but it is not responding for 404 errors. I am not able to work it out. How can I handle these types of errors?
Some webservers will return a webpage for a 404 error, which loads correctly, and therefore the webview did not fail to load.
This could be why you're seeing this behaviour.
There is no simple way to get at the webview's URLConnection in order to respond to the status code call backs.
If you really need to show an alert when a 404 in encountered instead of letting the webserver show it's own 404 page, then you could create an NSURLConnection and NSURLRequest yourself for the URL you wish to load.
You could then download the HTML and put it into a webview manually if it's successful. This will give you control over the URLConnection delegate and let you respond to a 404 response code as well.
#pragma mark -
#pragma mark - UIWebView Delegate Methods
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
static BOOL isRequestWeb = YES;
if (isRequestWeb) {
NSHTTPURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
if (response.statusCode == 404) {
// code for 404
return NO;
} else if (response.statusCode == 403) {
// code for 403
return NO;
}
[webView loadData:data MIMEType:@"text/html" textEncodingName:nil baseURL:[request URL]];
isRequestWeb = NO;
return NO;
}
return YES;
}
精彩评论