0

We know that we can share cookies between WKWebViews as discussed here and also in other discussions.

But is it possible to share cookies between a WKWebView and a UIWebView?

Both Http cookies and other cookies.

Did anyone managed to do that?

Rahatur
  • 3,147
  • 3
  • 33
  • 49

1 Answers1

0

Is it possible to share cookies between a WKWebView and a UIWebView?

The problem with WKWebView cookies is that requests made by WKWebView do not automatically carry cookies stored in the NSHTTPCookieStorage container.

Solution:

WKWebView Cookie injection is achieved by copying the contents of NSHTTPCookieStorage into WKHTTPCookieStore before executing WKWebView.loadReques() . The sample code is as follows:

CopyCookieToWebviewWithHandler(() =>
{
    NSUrl url = new NSUrl("xxx");
    NSUrlRequest request = NSUrlRequest.FromUrl(url);
    webView.LoadRequest(request);
}); 

void CopyCookieToWebviewWithHandler(Action completionHandler)
{

   NSHttpCookie[] cookies = NSHttpCookieStorage.SharedStorage.Cookies;

   WKHttpCookieStore cookieStore = webView.Configuration.WebsiteDataStore.HttpCookieStore;


   if(cookies.Length==0)
    {
        completionHandler();
        return;
    }

   foreach (NSHttpCookie cookie in cookies)
    {
      cookieStore.SetCookie(cookie,() =>
        {
          if(cookies[cookies.Length-1]==cookie)
           {
              completionHandler();
              return;
           }

        });
     }

 } 

Note:WKHttpCookieStore will only available after iOS 11.0

Lucas Zhang
  • 18,630
  • 3
  • 12
  • 22
  • I have tried everything, but not all cookie are reliably set in wkwebview. As described in https://stackoverflow.com/a/49534854/1252151 the cookies must be set before before instantiating the wkwebview. I just don't know how???? – Munk Sep 25 '19 at 22:14