Losing cookies in WKWebView

jiri.huml picture jiri.huml · Nov 20, 2014 · Viewed 14.4k times · Source

When I create new request for WKWebView with authentication cookie and send the request, WKWebView correctly loads protected web page:

let req = NSMutableURLRequest(URL: NSURL(string: urlPath)!)
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies([myAuthCookie]);
req.allHTTPHeaderFields = headers;
webView.loadRequest(req)

The problem is, that when user clicks on a any link in the web page, with new request WKWebView loses authentication cookie and is redirected to logon page. Cookie domain and path are filled and correct.

I am aware of the missing functionality of WKWebView mentioned here.

Thanks in advance for any idea.

Answer

The Windwaker picture The Windwaker · Dec 9, 2015

The best thing to do is to store your cookie into the

[NSHTTPCookieStorage sharedHTTPCookieStorage]

Then each time you want to load the request, call this function instead:

- (void)loadRequest:(NSURLRequest *)request {
        if (request.URL) {
            NSDictionary *cookies = [NSHTTPCookie requestHeaderFieldsWithCookies:[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:request.URL]];
            if ([cookies objectForKey:@"Cookie"]) {
                NSMutableURLRequest *mutableRequest = request.mutableCopy;
                [mutableRequest addValue:cookies[@"Cookie"] forHTTPHeaderField:@"Cookie"];
                request = mutableRequest;
            }
        }

        [_wkWebView loadRequest:request];
}

It extract the right cookies from shared cookies and includes it into your request