Anyone successfully passed cookies to WkWebView?

I have been working on a Custom WebView that on iOS uses the native WkWebView instead of the default.
My pain is that passing cookies to it from a HttpClient does not always sent those cookies on first request.
The intention is that the user, already being logged in using a HttpClient, opens a page showing the webpage of our service. By reusing the cookies, the user does not need to authenticate again. But by using the WkWebView, I sometimes end up on the loginpage, as a result of cookies not being passed properly.

This is my iOS Custom Renderer for the WebView:

public class CustomWebViewRenderer : ViewRenderer<CustomWebView, WKWebView>
{
    protected override async void OnElementChanged(ElementChangedEventArgs<CustomWebView> e)
    {
        base.OnElementChanged(e);

        if (e.NewElement != null)
        {
            if (Control == null)
            {
                var config = new WKWebViewConfiguration();

                var jCookies = Appl.FlurlClient.Cookies.Values;

                NSHttpCookie[] nsHttpCookies = jCookies.Where(c => c != null).Select(c => new NSHttpCookie(c)).ToArray();

                foreach (var c in nsHttpCookies)
                {
                    await config.WebsiteDataStore.HttpCookieStore.SetCookieAsync(c);
                }

                var webView = new WKWebView(Frame, config);
                SetNativeControl(webView);
            }
            Control.LoadRequest(new NSUrlRequest(new NSUrl(Element.Uri)));
        }
    }
}
Tagged:

Best Answer

Answers

  • SpunkMunkSpunkMunk Member ✭✭

    Thanks a lot! Just what I needed.

  • SpunkMunkSpunkMunk Member ✭✭

    HttpCookieStore is not supported on iOS 10. Any suggestions to a solution?

Sign In or Register to comment.