Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@cikichen
Forked from markcerqueira/WKWebViewCookie.m
Created February 15, 2019 03:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cikichen/8782f54c0cf5b984819e26f2410cd715 to your computer and use it in GitHub Desktop.
Save cikichen/8782f54c0cf5b984819e26f2410cd715 to your computer and use it in GitHub Desktop.
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment