1

I am using WKWebView for iOS 8 devices and want to check if the error occuring is NSURLErrorDomain then I want to make some changes, until now, I have added below code, but somehow the compiler goes into else part, now sure why.

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    if ( [error domain] == NSURLErrorDomain )
    {
        //code here
    }
    else
    {
        //But compiler always comes here
    }
 }

The error I do get is 'NSURLErrorDomain', but compiler is not executing if loop and goes in else part. Can anyone tell me why it is?

Larme
  • 24,190
  • 6
  • 51
  • 81
Pankaj Gaikar
  • 2,357
  • 1
  • 23
  • 29

2 Answers2

9

The domain property is an NSString, so you need to compare it like this:

if ([[error domain] isEqualToString:NSURLErrorDomain]) {

To give an idea of how the developers at Apple would handle this, check the code below which is copied from the Error Handling Programming Guide, listing 2-3:

NSString *errorMsg;
if ([[error domain] isEqualToString:NSURLErrorDomain]) {
    switch ([error code]) {
        case NSURLErrorCannotFindHost:
            errorMsg = NSLocalizedString(@"Cannot find specified host. Retype URL.", nil);
            break;
        case NSURLErrorCannotConnectToHost:
            errorMsg = NSLocalizedString(@"Cannot connect to specified host. Server may be down.", nil);
            break;
        case NSURLErrorNotConnectedToInternet:
            errorMsg = NSLocalizedString(@"Cannot connect to the internet. Service may not be available.", nil);
            break;
        default:
            errorMsg = [error localizedDescription];
            break;
    }
} else {
    errorMsg = [error localizedDescription];
}
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
  • Domain property is NSString. But NSURLErrorDomain's property is int. Then how it works.. Please check your answer.. – V.J. Jul 09 '15 at 11:57
  • 1
    No, [`NSURLErrorDomain`](https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/index.html#//apple_ref/doc/constant_group/NSURL_Domain) is an `NSString` as well. – Glorfindel Jul 09 '15 at 12:00
  • This does work, Thank you @Glorfindel – Pankaj Gaikar Jul 09 '15 at 12:49
0

According to the Apple Documentation the domain value will be @"NSURLErrorDomain" with an error code defined by the enum starting with NSURLErrorXxx.

Therefore you want:

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    if ([[error domain] isEqualToString:@"NSURLErrorDomain"] &&
        [error code] == NSURLErrorTimedOut )    // for example
    {
        // Handle timeout
    }
    else
    {
        // Some other error
    }
 }
Droppy
  • 9,691
  • 1
  • 20
  • 27