检测 WKWebview 何时无法处理请求

Detect when WKWebview cannot handle a request

我有以下代码

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;

代表:

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

工作正常,我可以在无法加载时捕获错误(404 等)。但是,当 nsurl 是 WKWebView 甚至无法处理的东西时,我该如何捕获错误?

例如:

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

将导致没有调用委托方法的空白页。我该如何处理检测到这个错误? (我已经检查过这个 iPhone SDK: Check validity of URLs with NSURL not working? 但我想知道是否有比正则表达式更好的东西?)

你可以试试看url是否可以这样请求:

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

if([NSURLConnection canHandleRequest:[NSURLRequest requestWithURL: nsurl]]){
    NSLog(@"URL can be loaded");
}else{
    NSLog(@"URL cannot be loaded");
}