【问题标题】:WKWebView catch HTTP error codes with Swift 4WKWebView 使用 Swift 4 捕获 HTTP 错误代码
【发布时间】:2018-03-16 13:21:19
【问题描述】:

此问题与以下问题相同:WKWebView catch HTTP error codes;不幸的是,Obj-C 中的方法不适用于 Swift 4,因此引用的 WKNavigationResponse.response 不再是 NSHTTPURLResponse 类型,因此它没有 http 状态代码。

但问题还是一样:我需要获取答案的http状态码来检测是否加载了预期的页面。

请注意,webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) delegate 不会在 404 的情况下被调用,但仅在网络问题(即服务器离线)的情况下才会被调用;而是调用 func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)

非常感谢您的回答。

【问题讨论】:

    标签: ios swift wkwebview


    【解决方案1】:

    WKWebView 上使用WKNavigationDelegate,您可以在每次收到响应时从响应中获取状态码。

    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse,
                 decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
    
        if let response = navigationResponse.response as? HTTPURLResponse {
            if response.statusCode == 401 {
                // ...
            }
        }
        decisionHandler(.allow)
    }
    

    【讨论】:

      【解决方案2】:

      HTTPURLResponseURLResponse 的子类。 “条件向下转换”的 Swift 方式是条件转换 as?,这可以与条件绑定 if let 结合使用:

      func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse,
                   decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
      
          if let response = navigationResponse.response as? HTTPURLResponse {
              if response.statusCode == 401 {
                  // ...
              }
          }
          decisionHandler(.allow)
      }
      

      【讨论】:

        猜你喜欢
        • 2018-02-24
        • 1970-01-01
        • 2017-06-20
        • 1970-01-01
        • 1970-01-01
        • 2019-05-18
        • 2016-04-07
        • 1970-01-01
        相关资源
        最近更新 更多