markhorrocks
markhorrocks

Reputation: 1418

Swift get headers from UIWebView response

I am unable to get headers from a UIWebView response as the response apparently hasn't been cached. Is there a workaround? I have tried code from here.

My application uses mixed native iOS view controllers and UIWebView. When I start a UIWebView session I write a cookie with the auth token from my key chain where the token is saved from the API login.

If the user navigates to another page in the web view the cookie doesn't appear to be correct. My goal is to get the auth cookie from each response and save it as the auth token from the server changes with every request. Then I want to add the token back into the new request.

The code below always returns nil. I'm trying to get an auth token from the headers.

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

Upvotes: 5

Views: 5958

Answers (1)

kuzdu
kuzdu

Reputation: 7524

Worked for Swift 3, Swift 4 and Swift 5

func webViewDidFinishLoad(_ webView: UIWebView) { 
    let headers = webView.request?.allHTTPHeaderFields
    for (key,value) in headers! {
        print("key \(key) value \(value)")
    } 
}

Upvotes: 1

Related Questions