Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Getting cookies into a WKWebView
// API reference: https://developer.apple.com/reference/webkit/webpolicydelegate/1536273-webview?language=objc
// Adapted from the Swift implementation: http://stackoverflow.com/a/32196541
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
if (![self requiresCookie:navigationAction]) {
decisionHandler(WKNavigationActionPolicyAllow);
return;
}
// Cookie is present so allow the request
if (([navigationAction.request.allHTTPHeaderFields objectForKey:@"Cookie"] != nil)) {
decisionHandler(WKNavigationActionPolicyAllow);
return;
}
// Take the existing request and cancel it, then make a copy of it with the cookie in it and load that instead
// https://bugs.webkit.org/show_bug.cgi?id=140191
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];
decisionHandler(WKNavigationActionPolicyCancel);
}
- (BOOL)requiresCookie:(WKNavigationAction *)navigationAction {
// Do work to determine if this navigation action requires a cookie
return YES;
}
@louis-lemon

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.