Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
            }
        }
    }
}
like image 316
markhorrocks Avatar asked Nov 09 '22 01:11

markhorrocks


1 Answers

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)")
    } 
}
like image 158
kuzdu Avatar answered Jan 04 '23 02:01

kuzdu