I have a Xamarin Forms app that uses cookies to track login status and uses both HTTPRequests and Webviews, so both need to share cookies. With UIWebView this cookies were shared without any extra management on my part; with WKWebView this appears not to be the case. I have been searching for an explanation on how cookies are handled with WKWebView or an example of how to manually retrieve and set the cookies between these two objects, but have been unable to find any. How do I get the cookie behavior that I have relied on when using UIWebView with WKWebView?
When I tried to implement a WKNamvigationDelegate the WebView OnLoadFinished was not called, so my loading indicator remained after loading was complete. What ended up working for me is in my iOS CustomWebViewRenderer's constructor I call this function to clear out any existing cookies and copy any cookies from the HTTP Shared Storage into the webview:
protected async void SetCookies()
{
var dataStore = WKWebsiteDataStore.DefaultDataStore;
var cookies = NSHttpCookieStorage.SharedStorage.Cookies;
var oldcookies = await dataStore.HttpCookieStore.GetAllCookiesAsync();
foreach (var cookie in oldcookies)
{
await dataStore.HttpCookieStore.DeleteCookieAsync(cookie);
}
foreach (var cookie in cookies)
{
await dataStore.HttpCookieStore.SetCookieAsync(cookie);
}
}
To get the cookies from the webview I have existing in shared code a CustomWebView that uses OnShouldLoad to detect the indication of a successful login, then call platform specific code. This was created to handle Android cookies, but will now work for iOS as well. The iOS implementation clears out any existing HTTP shared storage cookies and copies the cookies from the webview into the Shared Storage.
public async Task GetCookiesFromWebview()
{
var dataStore = WKWebsiteDataStore.DefaultDataStore;
var cookies = await dataStore.HttpCookieStore.GetAllCookiesAsync();
var oldcookies = NSHttpCookieStorage.SharedStorage.Cookies;
foreach (var cookie in oldcookies)
{
NSHttpCookieStorage.SharedStorage.DeleteCookie(cookie);
}
foreach (var cookie in cookies)
{
NSHttpCookieStorage.SharedStorage.SetCookie(cookie);
}
return;
}