Reputation: 177
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
var req = navigationAction.request;
let cookie = req.value(forHTTPHeaderField: "Cookie");
print(cookie) // always nil
decisionHandler(.allow);
}
I want to get the session after user login, but the cookie is always nil;how can I get it ?
Upvotes: 2
Views: 2668
Reputation: 1375
Why don't use WKWebView
's API that appeared since iOS 11
webView.configuration.websiteDataStore.httpCookieStore.getAllCookies() { cookies in
// do what you need with cookies
}
One advantage is that this method tracks HttpOnly cookies as well.
Upvotes: 2
Reputation: 1855
Cookie is generally stored in variable document.cookie in browser.
You can access it by executing Javascript code. In this case simply "document.cookie"
would return the cookies.
let cookieScript = "document.cookie;"
webView.evaluateJavaScript(cookieScript) { (response, error) in
if let response = response {
print(response as! String)
}
}
Upvotes: 3