I am developing an app which uses mixed native view controllers and UIWebView
. App sign in is handled by API and I have a utility function to save the auth token to a cookie in HTTPCookieStorage
as well as to a persistent user model.
Now I want to update to WKWebView
but it doesn't automatically load cookies from HTTPCookieStorage
like UIWebView
.
I found a way to save the response cookies from an answer here and I can modify the answer to also store the auth token to my user model but I'm not sure how I can use the cookies for a new request. I only need to add the cookie to the initial load as I will disable navigation in the web view.
Is there a way I can add the cookie value to the header or another solution?
Here is the code I will use to get the cookie from the response.
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
if let urlResponse = navigationResponse.response as? HTTPURLResponse,
let url = urlResponse.url,
let allHeaderFields = urlResponse.allHeaderFields as? [String : String] {
let cookies = HTTPCookie.cookies(withResponseHeaderFields: allHeaderFields, for: url)
HTTPCookieStorage.shared.setCookies(cookies , for: urlResponse.url!, mainDocumentURL: nil)
decisionHandler(.allow)
}
}