2

I have the following code

NSURL *nsurl = [NSURL urlWithString:@"http://url.that.does.not.exist.com"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:nsurl];
WKWebViewConfiguration *config = [WKWebViewConfiguration new];
WKWebView *wv = [[WKWebView alloc] initWithFrame:[[UIScreen mainScreen] bounds] configuration:config];
wv.navigationDelegate = self;

And the delegate:

- (void)webView:(WKWebView *)webView
     decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse
                       decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
...
}

Works fine and I can catch errors when the could not be loaded (404, etc). But how do I catch the error when the nsurl was something WKWebView cannot even handle?

For example:

NSURL *nsurl = [NSURL urlWithString:@"nacho"];

will lead to a blank page with no delegate method being called. How can I handle detect this error? (I have checked at this iPhone SDK: Check validity of URLs with NSURL not working? but I wonder if there is anything better than regex?)

Community
  • 1
  • 1
nacho4d
  • 43,720
  • 45
  • 157
  • 240

1 Answers1

2

You can try and see if the url can be requested like this:

NSURL *nsurl = [NSURL urlWithString:@"nacho"];

if([NSURLConnection canHandleRequest:[NSURLRequest requestWithURL: nsurl]]){
    NSLog(@"URL can be loaded");
}else{
    NSLog(@"URL cannot be loaded");
}
Karim H
  • 1,543
  • 10
  • 24
  • That works!. It is in NSURLConnection.h there is a big "/*** DEPRECATED: The NSURLConnection class should no longer be used. NSURLSession is the replacement for NSURLConnection ***/" I wonder if there is a better (non deprecated) approach... – nacho4d Jun 18 '16 at 14:51
  • according to apple https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/index.html#//apple_ref/occ/cl/NSURLConnection the **NSURLConnection** is not totally DEPRECATED. there is still a non DEPRECATED methods – Karim H Jun 18 '16 at 15:01