我怎样才能从 didFailProvisionalNavigation 方法失败 URL

How can I get failed URL from didFailProvisionalNavigation method

我正在尝试为我的网络视图显示错误消息,我需要知道 url 哪个不可用,所以我实现了委托方法:

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    [self.addressBar finishLoadingProgressAnimated:YES];
    NSLog(@"%@", webView.URL);
    [self showErrorPageForURL:error.userInfo[NSErrorFailingURLStringKey]];
}

但是 NSErrorFailingURLStringKey 已被弃用,所以我怎么会失败 URL? WKNavigation 的界面是空的。 webView.URL == 那一刻没有。

您可以用NSURLErrorFailingURLStringErrorKey代替NSErrorFailingURLStringKey。如果你跳到它在Xcode中的定义,你会发现下面的讨论。

This constant supersedes NSErrorFailingURLStringKey, which was deprecated in Mac OS X 10.6. Both constants refer to the same value for backward-compatibility, but this symbol name has a better prefix.

Swift 3 或 Swift 4

func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
    if error._domain == "WebKitErrorDomain" {
        if let info = error._userInfo as? [String: Any] {
            if let url = info["NSErrorFailingURLKey"] as? URL {

            }
            if let urlString = info["NSErrorFailingURLStringKey"] as? String {

            }
        }
    }
}