Get HTTP Response header on UIWebView

How can I get HTTP headers response from WebView? I’ve found semi-solutions at Stackoverflow, but it’s written on Objective-C and can’t convert it to Swift (I’ve tried with my poor Obj-C knowledge).

Objective-C code:

  • NSArray full of NSDictionaries. How to find index of object?
  • how to retrieve all visible table section header views
  • Google Map SDK: Draw correct polyline in google map as Device Moves in Background
  • Issue using CCCrypt (CommonCrypt) in Swift
  • How to prevent circular reference when Swift bridging header imports a file that imports Hopscotch-Swift.h itself
  • Style all UITextFields at once rather than in each ViewController?
  • - (void)webViewDidFinishLoad:(UIWebView *)webView {
        NSCachedURLResponse *resp = [[NSURLCache sharedURLCache] cachedResponseForRequest:webView.request];
        NSLog(@"%@",[(NSHTTPURLResponse*)resp.response allHeaderFields]);
    }
    
    1. How that code will look at Swift?
    2. Maybe now we have better ways to do so? Caching is not always enabled.

    2 Solutions Collect From Internet About “Get HTTP Response header on UIWebView”

    Swift

    Swift is more stringent ; you want to protect yourself against nil pointers and optionals:

    • check that the webView actually has a request
    • check that the request actually has a NSCachedURLResponse
    • type-check the response against 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)
                }
            }
        }
    }
    

    Just using this in 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)
                    }
                }
            }