WKWebView did't give all cookies in navigationResponse

為{幸葍}努か 提交于 2019-12-01 19:41:02

问题


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)
    }

来源:https://stackoverflow.com/questions/41217020/wkwebview-didt-give-all-cookies-in-navigationresponse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!