如何从WKWebView获取cookie?

时间:2015-01-30 09:37:16

标签: ios macos cookies wkwebview

如何从WKWebView实例获取所有 cookie?

以下是我迄今为止所做的尝试:

1 个答案:

答案 0 :(得分:4)

由于这个问题在一年后没有得到解答,我发布了我的不完善但有效的解决方案:

您可以NSHTTPURLResponse上定义的- webView:decidePolicyForNavigationResponse:decisionHandler:方法访问WKNavigationDelegate个对象。您可以稍后从HTTP标头中手动提取Cookie:

- (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);
}

如果你有更好的解决方案,请发布你的解决方案。