WKWebView did't give all cookies in navigationResponse

871 views Asked by At

I am trying to replace my working UIWebView project with WkWebView. I've seen many posts but i did't get any good solution for getting all cookies from WKWebView. I've also tried this evaluateJavaScript:@"document.cookie;" but it gives me this (). I also checked this post and also tried this solution as i understood but it also did't works.

guard let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies else { return } Above method is only works with UIWebView because WKWebView does not write back the cookies immediately. Can any one please tell how i can get all cookies form WKWebView. Thanks

This Method works but did't give me all cookies.

func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {

        if navigationResponse.response.url?.absoluteString.range(of: "") != nil || navigationResponse.response.url?.absoluteString.range(of: "") != nil{

            let response = navigationResponse.response as? HTTPURLResponse
            let cookies = HTTPCookie.cookies(withResponseHeaderFields: response?.allHeaderFields as! [String : String], for: (response?.url)!)

            var array = [[HTTPCookiePropertyKey : Any]]()
            for cookie in cookies {
                if let properties = cookie.properties {
                    print("cookies save")
                    array.append(properties)
                }
            }
            sCookies.append(array)
            accountsUserDefaults.set(sCookies, forKey: "sCookies")
            UserDefaults.standard.synchronize()
        }

        decisionHandler(WKNavigationResponsePolicy.allow)
    }
0

There are 0 answers