Swift get headers from a UIWebView response

I cannot get the headers from the UIWebView response, as the answer did not seem to be cached. Is there a workaround? I tried the code from here .

My application uses mixed view controllers for iOS and UIWebView. When I start a UIWebView session, I write a cookie with an auth token from my keychain, where the token is saved from the API entry.

If the user navigates to another page in the web view, the cookie does not display correctly. My goal is to get an auth cookie from each response and save it, since the authentication token from the server changes with every request. Then I want to add the marker back to the new request.

The code below always returns nil. I am trying to get authentication token from 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)
            }
        }
    }
}
+5
1

Swift 3, Swift 4 Swift 5

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

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


All Articles