I am embedding a WKWebView in my app. It uses a PHP session cookie to identify the user. I get the session cookie with the following call:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[NSJSONSerialization dataWithJSONObject:jsonobject options:0 error:&err]];
NSHTTPURLResponse *response = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
Based on this: Can I set the cookies to be used by a WKWebView? I add the cookies to the document
for (NSHTTPCookie* cookie in [NSHTTPCookieStorage sharedHTTPCookieStorage].cookies)
{
NSString *javascript = [NSString stringWithFormat:@"document.cookie = '%@=%@';", [cookie name], [cookie value]];
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
WKUserContentController *ucController = [[WKUserContentController alloc] init];
WKProcessPool *processPool = [[WKProcessPool alloc] init];
config.processPool = processPool;
config.userContentController = ucController;
[ucController addUserScript:[[WKUserScript alloc] initWithSource:javascript injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO]];
}
And I manually set the session cookie in the initial load request:
NSMutableURLRequest *pageLoadRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[pageLoadRequest setHTTPMethod:@"GET"];
[pageLoadRequest setHTTPShouldHandleCookies:YES];
[pageLoadRequest setAllHTTPHeaderFields:[NSHTTPCookie requestHeaderFieldsWithCookies:[NSHTTPCookieStorage sharedHTTPCookieStorage].cookies]];
[_webView loadRequest:pageLoadRequest];
My problem is that AJAX requests will not contain the session cookie.