WKWebView does not send session cookies

I embed WKWebView in my application. It uses a PHP session cookie to identify the user. I get a 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 cookies to use WKWebView? I am adding 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 bootstrap 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 session cookies.

+5
source share
1 answer

Perhaps your cookies are sent as Set-Cookie in response 302. Try YWKWebView to simply replace your WKWebView .

0
source

All Articles