this question is identical to the following: WKWebView catch HTTP error codes; unfortunately the methods in Obj-C are not applicable to Swift 4, thus the cited WKNavigationResponse.response
is no longer of type NSHTTPURLResponse
so it doesn't have the http status code.
But the issue is still the same: I need to get the http status code of the answer to detect if the expected page is loaded or not.
Please note that webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error)
delegate is not called in case of 404
but only in case of network issue (i.e. server offline); the func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)
is called instead.
Thanks a lot for your answers.
Bookmark this question. Show activity on this post. this question is identical to the following: WKWebView catch HTTP error codes; unfortunately the methods in Obj-C are not applicable to Swift 4, thus the cited WKNavigationResponse.response is no longer of type NSHTTPURLResponse so it doesn't have the http status code.
Using a WKNavigationDelegate on the WKWebView you can get the status code from the response each time one is received. func webView (_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) { if let response = navigationResponse.response as?
Instead the error reported is simply "Script error." The Safari Web Inspector is the best choice to debug WKWebView error messages for webpages that you do not control. Follow these steps to open the Safari Web Inspector during app development:
You can ensure Javascript is enabled using: One method to capture Javascript errors from a WKWebView uses WKScriptMessageHandler and WKUserContentController. First, create a WKScriptMessageHandler by calling the add (_:, name:) method on the WKWebView.userControllerController:
Using a WKNavigationDelegate
on the WKWebView
you can get the status code from the response each time one is received.
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
is a subclass of URLResponse
. The Swift way of “conditional downcasting” is the conditional cast as?
, this can be combined with conditional binding 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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With