I am developing an application that uses mixed view and visible controllers UIWebView. The input to the application is processed by the API, and I have a utility function to save the auth token in cookie in HTTPCookieStorage, as well as in the user's constant model.
Now I want to upgrade to WKWebView, but it will not automatically load cookies from HTTPCookieStoragelike UIWebView.
I found a way to save the response cookies from the response here , and I can change the answer to save the authentication token in my user model, but I do not know how I can use cookies for a new request. I only need to add a cookie to the bootstrap, since I will disable navigation in the web view.
Is there a way to add a cookie value to the header or another solution?
Here is the code that 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)
}
}
source
share