Get HTTP response header in UIWebView

How to get HTTP headers response from WebView? I have found the half-solutions of https://stackoverflow.com/a/166269/167169/ , but it is written in Objective-C and cannot convert it to Swift (I tried with my poor Obj-C knowledge).

Objective-C code:

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSCachedURLResponse *resp = [[NSURLCache sharedURLCache] cachedResponseForRequest:webView.request];
    NSLog(@"%@",[(NSHTTPURLResponse*)resp.response allHeaderFields]);
}
  • How will this code look like on Swift?
  • Perhaps we now have better ways to do this? Caching is not always enabled.
+2
source share
2 answers

Swift

Swift is more strict; you want to protect yourself from pointers niland optionals:

  • make sure to webViewhaverequest
  • make sure to requesthaveNSCachedURLResponse
  • check response type on NSHTTPURLResponse
func webViewDidFinishLoad(webView: UIWebView) {
    if let request = webView.request {
        if let resp = NSURLCache.sharedURLCache().cachedResponseForRequest(request) {
            if let response = resp.response as? NSHTTPURLResponse {
                print(response.allHeaderFields)
            }
        }
    }
}
+3
source

SWIFT 3.1:

if let request = webView.request {
            if let resp = URLCache.shared.cachedResponse(for: request) {
                if let response = resp.response as? HTTPURLResponse {
                    print(response.allHeaderFields)
                }
            }
        }
0

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


All Articles