WKWebView 使用 Swift 4 捕获 HTTP 错误代码
WKWebView catch HTTP error codes with Swift 4
此问题与以下问题相同:;不幸的是,Obj-C 中的方法不适用于 Swift 4,因此引用的 WKNavigationResponse.response
不再是 NSHTTPURLResponse
类型,因此它没有 http 状态代码。
但问题还是一样:我需要获取答案的 http 状态代码以检测是否加载了预期的页面。
请注意,webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error)
委托不会在 404
的情况下调用,而只会在网络问题(即服务器离线)的情况下调用; func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)
被调用。
非常感谢您的回答。
在 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)
}
HTTPURLResponse
是 URLResponse
的子类。 “条件向下转型”的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)
}
此问题与以下问题相同:WKNavigationResponse.response
不再是 NSHTTPURLResponse
类型,因此它没有 http 状态代码。
但问题还是一样:我需要获取答案的 http 状态代码以检测是否加载了预期的页面。
请注意,webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error)
委托不会在 404
的情况下调用,而只会在网络问题(即服务器离线)的情况下调用; func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)
被调用。
非常感谢您的回答。
在 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)
}
HTTPURLResponse
是 URLResponse
的子类。 “条件向下转型”的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)
}