Getting HTTP Response Headers from WKWebview

I need to read the HTTP response headers from the request WKWebview. I need to make settings based on specific user headers sent by the server. Cannot add this information to response data.

I could not find the entry in the documentation or in previous questions. Is there any way to do this?

+9
source share
4 answers

It looks like you can get a response from the method WKNavigationDelegate webView:decidePolicyFor:decisionHandler:.

Define some object as WKWebView navigationDelegateand add this method:

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    NSDictionary *headers = ((NSHTTPURLResponse *)navigationResponse.response).allHeaderFields;

    decisionHandler(WKNavigationResponsePolicyAllow);
}
+13
source

Swift 3.1 version of NobodyNada answer:

Without power

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 the use of force:

func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
    let headers = (navigationResponse.response as! HTTPURLResponse).allHeaderFields
    //do something with headers 
    decisionHandler(.allow)
}
+9
source

(WKNavigationResponse*)navigationResponse. navigationResponse :

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {

     NSHTTPURLResponse * response = (NSHTTPURLResponse *)navigationResponse.response;

}
+1
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)
}
0

Source: https://habr.com/ru/post/1663667/


All Articles