【问题标题】:Detect when WKWebview cannot handle a request检测 WKWebview 何时无法处理请求
【发布时间】:2016-10-20 05:20:27
【问题描述】:

我有以下代码

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?,但我想知道有没有比正则表达式更好的东西?)

【问题讨论】:

    标签: ios cocoa nsurl nsurlrequest wkwebview


    【解决方案1】:

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

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

    【讨论】:

    • 这行得通!。它在 NSURLConnection.h 中有一个很大的“/*** 已弃用:不应再使用 NSURLConnection 类。NSURLSession 是 NSURLConnection ***/ 的替代品”我想知道是否有更好的(非弃用)方法。 ..
    • 根据苹果developer.apple.com/library/ios/documentation/Cocoa/Reference/… 的说法,NSURLConnection 并未完全弃用。还有一个非 DEPRECATED 方法
    猜你喜欢
    • 1970-01-01
    • 2013-06-13
    • 1970-01-01
    • 2016-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    • 2016-02-17
    相关资源
    最近更新 更多