为什么WKWebView没有返回所有cookie?

时间:2018-01-11 11:09:13

标签: ios cookies uiwebview wkwebview

您好我用WKWebview替换了UIWebview。因为在多帧加载UIWebview keyborad是解雇。所以我使用了WKWebView。我的问题现在消失了。

但是在WKWebView上我没有得到cookie。它只返回JSESSIONID cookie,在UIWebView上获取所有cookie。

请帮我解决这个问题。

这是我的启动WKWebView的代码片段。

   func startWebView() {
        URLCache.shared.removeAllCachedResponses()
        if webView == nil {

            let source =
                "var meta = document.createElement('meta'); " +
                    "meta.name = 'viewport'; " +
                    "meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no'; " +
                    "var head = document.getElementsByTagName('head')[0]; " +
            "head.appendChild(meta);"

            let script = WKUserScript(source:source,
                                      injectionTime: .atDocumentEnd,
                                      forMainFrameOnly: true)

            let userContentController = WKUserContentController()
            userContentController.addUserScript(script)

            let configuration = WKWebViewConfiguration()
            configuration.userContentController = userContentController
            let prefs = WKPreferences()
            prefs.javaScriptEnabled = true
            configuration.preferences = prefs
            webView = WKWebView(frame: CGRect.zero, configuration: configuration)

            webView.navigationDelegate = self
            webView.allowsBackForwardNavigationGestures = true

            webContainerView.addSubview(webView)
            webView.translatesAutoresizingMaskIntoConstraints = false

            let vdict = ["WV": webView!]
            webContainerView.addConstraints(
                NSLayoutConstraint.constraints(withVisualFormat: "H:|[WV]|",
                                               options: [], metrics: nil,
                                               views: vdict)
            )
            webContainerView.addConstraints(
                NSLayoutConstraint.constraints(withVisualFormat: "V:|[WV]|",
                                               options: [], metrics: nil,
                                               views: vdict)
            )

        }
        var urlstr = LoginServer.url.absoluteString
        //#if DEBUG

        let url : URL = URL(string: urlstr)!
        var urlRequest = URLRequest(url: url,
                                    cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData,
                                    timeoutInterval: 60.0)
        if Reachability.shared.isNetworkAvailable(){
            urlRequest.cachePolicy = .reloadRevalidatingCacheData
            _ = webView.load(urlRequest)

        }
        else{
            loadingIndicator.stopAnimating()
            loadingIndicator.isHidden = true
        }

    }

以下是获取Cookie的代码

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

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

            for cookie in cookies {
                print(cookie.description)
                print("found cookie " + cookie.name + " " + cookie.value)
            }
        }
    }


        decisionHandler(.allow)

}

1 个答案:

答案 0 :(得分:-1)

您应该可以使用以下代码访问所有Cookie

let cookies = HTTPCookieStorage.shared.cookies
for cookie in cookies! {
    print(cookie.description)
    print("found cookie " + cookie.name + " " + cookie.value)
}

以下是我的网络视图控制器的摘要

class MyWebViewController: UIViewController, WKNavigationDelegate, WKScriptMessageHandler {

    override func viewDidLoad() {
        super.viewDidLoad()

        // create WKWebViewConfiguration
        let webViewConfig = WKWebViewConfiguration()
        let userContentController = WKUserContentController();
        userContentController.add(self, name: "myApp")
        webViewConfig.userContentController = userContentController

        // init and load request in webview.
        webView = WKWebView(frame: self.view.frame, configuration:webViewConfig)
        webView.navigationDelegate = self
        webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        self.view.addSubview(webView)

        let request = URLRequest(url: webAddress)
        webView.load(request)
    }

    //
    // WKNavigationDelegate
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler:@escaping ((WKNavigationActionPolicy) -> Void)) {
        print("decidePolicyForNavigationAction with url:\(String(describing: navigationAction.request.url!))")

        if let url = navigationAction.request.url {
            // url request is outside of my website, then use safari to view address
            if webAddress.host != url.host {
                UIApplication.shared.open(url)
                decisionHandler(.cancel)
            }
        }
        decisionHandler(.allow)
    }

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

        let cookies = HTTPCookieStorage.shared.cookies
        for cookie in cookies! {
            print(cookie.description)
            print("found cookie " + cookie.name + " " + cookie.value)
        }
        decisionHandler(.allow)
    }

    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    }

    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        print("Navigation error :\(error.localizedDescription)")
    }

    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        print("Loading error :\(error.localizedDescription)")
    }

    //
    // WKScriptMessageHandler
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    }

    var webView: WKWebView!
    var config = ResolveConfig()
    let webAddress = URL(string:"https://mywebaddr.com")!
}