Retrieve HTTP response headers from WKWebview
It looks like you can access the response from the WKNavigationDelegate
method webView:decidePolicyFor:decisionHandler:
.
Set some object as the WKWebView
's navigationDelegate
, and add this method:
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
NSDictionary *headers = ((NSHTTPURLResponse *)navigationResponse.response).allHeaderFields;
decisionHandler(WKNavigationResponsePolicyAllow);
}
Swift 3.1, 4, and 5 version of NobodyNada's answer:
Without force cast
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
if let response = navigationResponse.response as? HTTPURLResponse {
let headers = response.allHeaderFields
//do something with headers
}
decisionHandler(.allow)
}
With force cast:
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
let headers = (navigationResponse.response as! HTTPURLResponse).allHeaderFields
//do something with headers
decisionHandler(.allow)
}
Swift 4.2 Answers with response.
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void)
{
let response = navigationResponse.response as? HTTPURLResponse
decisionHandler(.allow)
}