Search code examples
iosobjective-cwkwebview

Retrieve HTTP response headers from WKWebview


I need to read the response HTTP headers from a WKWebview's request. I need to perform customizations based on certain custom headers sent by the server. It's not possible to add this information in the response data.

I could not find any entry in the documentation nor in previous questions here. Is there any way to do that?


Solution

  • 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);
    }