Siyu Song
Siyu Song

Reputation: 917

How to get cookies from WKWebView?

How do I get all cookies from a WKWebView instance?

Here are what I've tried so far:

Upvotes: 7

Views: 5469

Answers (1)

Siyu Song
Siyu Song

Reputation: 917

Since this question hasn't been answered after one year, I am posting my imperfect, but working solution:

You can have access to an NSHTTPURLResponse object in - webView:decidePolicyForNavigationResponse:decisionHandler: method defined on WKNavigationDelegate. You can later extract the cookies manually from the HTTP header:

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    NSHTTPURLResponse* response = navigationResponse.response;
    NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[NSURL URLWithString:@""]];
    for (NSHTTPCookie *cookie in cookies) {
        // Do something with the cookie
    }

    decisionHandler(WKNavigationResponsePolicyAllow);
}

Please post your solution if you have a better one.

Upvotes: 4

Related Questions