Reputation: 3629
I'm trying to figure out how best to determine if a page is available in iOS. I've got a WKWebView that can see URL Request codes, which works fine for 404, 500, etc. However I'm not sure how to handle requests to a URL when the intended URL's server may be down. My WKWebView start navigation delegate method fires, and then nothing. My web request just seems to disappear.
Chrome for example returns a message saying "This site can’t be reached chess.math.science.google.com’s server IP address could not be found."
I've included the iOS Reachability class in my didStartProvisionalNavigation
delegate method and that is saying the URL should be reachable via WIFI, which while not incorrect, does not check if the URL has anything to return.
App Log:
2018-03-23 16:28:54.142105-0400 MyApp[1245:774884] INTERNET REACHABLE
2018-03-23 16:28:54.272582-0400 MyApp[1245:774884] WKWEBVIEW DID START NAVIGATION
2018-03-23 16:28:54.274085-0400 MyApp[1245:774884] NETWORK STATUS FOR URL chess.math.science.google.com: 2
(lldb) po netStatus
ReachableViaWiFi
Code:
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
NSLog(@"WKWEBVIEW DID START NAVIGATION");
Reachability* tinyReach = [Reachability reachabilityWithHostname:webView.URL.absoluteString];
NetworkStatus netStatus = [tinyReach currentReachabilityStatus];
NSLog(@"NETWORK STATUS FOR URL %@: %li", webView.URL.absoluteString, netStatus);
if(netStatus == NotReachable) {
NSLog(@"NOT REACHABLE");
Upvotes: 1
Views: 1027
Reputation: 6290
You need to implement webView:didFailProvisionalNavigation:withError:
method of WKNavigationDelegate. ( See https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455637-webview?language=objc ) and then set your delegate on the web view:
self.webView.navigationDelegate = myDelegate; // maybe self
This method reports network errors including a timeout error and DNS resolution errors. They usually have an error.domain = NSURLErrorDomain (NSString) and error.code from NSURLErrorDomain enum.
For example, if a server doesn't respond for 60 seconds for whatever reason, you'll get NSURLErrorTimedOut, also there are many others possible errors like NSURLErrorCannotConnectToHost and NSURLErrorNotConnectedToInternet. The list is here or in the NSURLError.h header.
P.S. Reachability API is more suitable for hinting the user that something might be wrong rather than using it as the primary source of truth. It is always better (and adviced by Apple engineers) to try running a request and getting a real error instead of relying on some reachability indications.
Upvotes: 3