如何在swift4中从WKWebView获取cookie值?

时间:2018-09-16 16:51:37

标签: ios cookies webview

我无法从该网站获取Cookie-“ https://bødekontrol.dk” 我正在使用xcode -9.4.1和iOS 11。 我遵循以下代码,

导入UIKit 导入WebKit 类ViewController:UIViewController {     var urlString =“ https://bødekontrol.dk”     var webView:WKWebView!     fileprivate var webViewIsInited = false     覆盖func viewDidLoad(){         super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
override func viewWillLayoutSubviews() {
    if !webViewIsInited {
        webViewIsInited = true
        if webView == nil {
            webView = WKWebView(frame: UIScreen.main.bounds, configuration: WKWebViewConfiguration())
        }

        view.addSubview(webView)
        webView.navigationDelegate = self
        webView.uiDelegate = self
        webView.loadUrl(string: urlString)
    }
}

} 扩展ViewController:WKNavigationDelegate {

func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
    decisionHandler(.allow)
    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)
            }
        }
    }

}

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

}

}

扩展ViewController:WKUIDelegate {

func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
    if navigationAction.targetFrame == nil {
        let vc = ViewController()
        vc.urlString = navigationAction.request.url?.absoluteString ?? "http://google.com"
        vc.view.frame = UIScreen.main.bounds
        vc.webView = WKWebView(frame: UIScreen.main.bounds, configuration: configuration)
        navigationController?.pushViewController(vc, animated: false)
        return vc.webView
    }
    return nil
}

}

扩展名WKWebView {

func loadUrl(string: String) {
    if let encoded = string.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
        let url = URL(string: encoded)
    {
        if self.url?.host == url.host {
            self.reload()
        } else {
            load(URLRequest(url: url))
        }
    }
}

}

1 个答案:

答案 0 :(得分:1)

实施此协议 WKHTTPCookieStoreObserver 并检查此协议的功能。

cookiesDidChange