xingchi
xingchi

Reputation: 177

how to get cookie from urlrequest in iOS wkwebview

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

Answers (2)

Sander
Sander

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

Rikesh Subedi
Rikesh Subedi

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

Related Questions