I use UIWebView to load web from a webLink and UIWebViewDelegate to control error state:
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:webLink]]];
- (void)webViewDidStartLoad:(UIWebView *)webView{
NSLog(@"START LOAD");
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSLog(@"FINISH LOAD");
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
NSLog(@"ERROR : %@",error);
}
But when webLink not found, it NOT go to didFailLoadWithError, it go to startLoad and didFinishLoad. How to go the situation when webLink not found?
Please help!
Unfortunately, 404 (or similar codes) aren’t considered errors by
UIWebView, because a HTML response was received. Worse, theUIWebViewdoesn’t capture response codes for us, so you have to do that manually, viaNSURLConnection. Here’s one way to deal with it:Note, in my implementation, I’m not only checking for status codes, but I’m also checking for redirects (which you may or may not want to do). I do this because some ISP’s intercept HTTP requests, and if the destination site is not found, redirect you to their own search web page (which I think is a bit creepy knowing that my ISP is checking out every web site I search for). And if you’re dealing with iPhones that are connecting via wifi, you have to deal with these vagaries.
So, for example, my code above is searching for “http://www.applecom/pages” (in which I deliberately omitted the period of “.com”, which should fail a DNS lookup), but for which my ISP, Verizon, intercepted the request and redirected by HTTP connection to their own search page and as such, my app is reporting:
You might want to think about what sort of redirects are acceptable (e.g., if you go to “www.adobephotoshop.com” and it redirects you to “www.adobe.com”) and what sorts aren’t (e.g., if I go to “www.applecom” and it redirects me to “search.dnsassist.verizon.net”. I may be worrying about a fairly narrow problem (which affects me because of my ISP), but it’s something to contemplate.