Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Getting cookies into a WKWebView
// API reference:
// Adapted from the Swift implementation:
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
if (![self requiresCookie:navigationAction]) {
// Cookie is present so allow the request
if (([navigationAction.request.allHTTPHeaderFields objectForKey:@"Cookie"] != nil)) {
// Take the existing request and cancel it, then make a copy of it with the cookie in it and load that instead
NSURL* url = navigationAction.request.URL;
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSDictionary *cookieProps = @{ NSHTTPCookieDomain: [url host], NSHTTPCookiePath : @"/",
NSHTTPCookieName : @"cookieName", NSHTTPCookieValue : @"cookieValue" };
NSDictionary *headerFields = [NSHTTPCookie requestHeaderFieldsWithCookies:@[[NSHTTPCookie cookieWithProperties:cookiesProps]]];
[request setAllHTTPHeaderFields:headerFields];
[request setHTTPShouldHandleCookies:YES];
[webView loadRequest:request];
- (BOOL)requiresCookie:(WKNavigationAction *)navigationAction {
// Do work to determine if this navigation action requires a cookie
return YES;

This comment has been minimized.

Copy link

@louis-lemon louis-lemon commented May 15, 2020

Thank you for sharing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment