4
votes

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)
    }
did you get any solution for this?. I too face the same problem. I couldn't get all the cookies. I am sure it gets the cookies, as it loads the site. I want to get the cookies and stop loading of the site.Rohan Bhale
@RohanBhale no i did't get any solution yet, i think there is no proper way to retreive cookies, and problem in api. I think we can get cookies if we use this class. ReferenceZAFAR007
I guess we will need to wait till we get the api as per the documentation from apple developer.apple.com/documentation/webkit/…Rohan Bhale