5

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)
            }
        }
    }
}
Community
  • 1
  • 1
markhorrocks
  • 1,199
  • 19
  • 82
  • 151

1 Answers1

1

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)")
    } 
}
kuzdu
  • 7,124
  • 1
  • 51
  • 69
  • This does not appear to be the response. – markhorrocks Mar 14 '17 at 15:31
  • What do you mean exactly? In webView.request?.allHTTPHeaderFields are all response headers of WebView Url – kuzdu Mar 14 '17 at 15:44
  • Maybe a false assumption by me. These are the only headers present. `key Accept value text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 key User-Agent value Mozilla/5.0 (iPhone; CPU iPhone OS 10_2 like Mac OS X) AppleWebKit/602.3.12 (KHTML, like Gecko) Mobile/14C89`. I expected to see an auth token plus the regular cookies. – markhorrocks Mar 14 '17 at 16:25
  • @markhorrocks Have you used a tool like Charles Proxy to look at the *actual* response and confirm that the fields you expect are really there? – Caleb Mar 14 '17 at 17:50
  • No, I'm kinda new at iOS coding. Ill try that. Thanks for the tip. – markhorrocks Mar 14 '17 at 19:48
  • This isn't giving me the cookie. – markhorrocks May 23 '17 at 15:31
  • When the cookie is inside the header, my code show what uiwebview get. Do you get the cookie with an external programm like postman? – kuzdu May 23 '17 at 18:59