I have Xamarin Forms WebView app for android. I'm able to use the app perfectly fine on first login. But if i re-open the app WebView cookies clear and user need to login again. I want that the user does not need to log in after they have logged in once, even if they close the application. Here is my code:
var wbURL = "https://www.example.com/login/";
webrowser.Source = wbURL;
CodePudding user response:
On Android, cookies should be stored automatically, unless you delete them manually using a custom renderer.
For iOS, you can save cookies and restore them later on, something like this:
Save cookies (Call this method after the user is logged in, this code is placed into the WebView custom renderer):
public async Task SaveCookies()
{
// For iOS < 10, cookies are saved in NSHTTPCookieStorage.sharedHTTPCookieStorage(), coojies should work withouth this
if (!UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
{
return;
}
try
{
var cookies = await Configuration.WebsiteDataStore.HttpCookieStore.GetAllCookiesAsync();
var cachedCookies = cookies.Select(c => new Cookie(c.Name, c.Value, c.Path, c.Domain)
{
Secure = c.IsSecure,
Version = Convert.ToInt32(c.Version)
}).ToList();
//TODO: Save the cachedCookies into app cache. You can create a service in the shared project
}
catch (Exception e)
{
}
}
Restore cookies (Call this in the WebView custom renderer OnElementChanged method):
var store = WKWebsiteDataStore.NonPersistentDataStore;
await RestoreCookies(store);
private async Task RestoreCookies(WKWebsiteDataStore store)
{
// For iOS < 10, cookies are saved in NSHTTPCookieStorage.sharedHTTPCookieStorage(), coojies should work withouth this
if (!UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
{
return;
}
if (store == null)
{
return;
}
await ClearCookies(store);
var storedCookies = //TODO: Retreive cookies from where you sotred them
foreach (Cookie cookie in storedCookies)
{
await store.HttpCookieStore.SetCookieAsync(new NSHttpCookie(cookie));
}
}
private async Task ClearCookies(WKWebsiteDataStore store)
{
var cookies = await store.HttpCookieStore.GetAllCookiesAsync();
if (cookies?.Any() ?? false)
{
foreach (NSHttpCookie cookie in cookies)
{
await store.HttpCookieStore.DeleteCookieAsync(cookie);
}
}
}
EDIT: If you have problems on Android as well, try this code in your WebView custom renderer:
var cookieManager = CookieManager.Instance;
cookieManager.SetAcceptCookie(true);
cookieManager.AcceptCookie();
cookieManager.Flush(); // Forces cookie sync