我有適用于 android 的 Xamarin Forms WebView 應用程式。我可以在第一次登錄時完美地使用該應用程式。但是,如果我重新打開應用程式 WebView cookie,并且用戶需要再次登錄。我希望用戶在登錄一次后不需要登錄,即使他們關閉了應用程式。這是我的代碼:
var wbURL = "https://www.example.com/login/";
webrowser.Source = wbURL;
uj5u.com熱心網友回復:
在 Android 上,cookie 應該自動存盤,除非您使用自定義渲染器手動洗掉它們。
對于 iOS,您可以保存 cookie 并在以后恢復它們,如下所示:
保存cookies(用戶登錄后呼叫該方法,這段代碼放在WebView自定義渲染器中):
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)
{
}
}
恢復 cookie(在 WebView 自定義渲染器 OnElementChanged 方法中呼叫此方法):
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);
}
}
}
編輯:如果您在 Android 上也有問題,請在您的 WebView 自定義渲染器中嘗試此代碼:
var cookieManager = CookieManager.Instance;
cookieManager.SetAcceptCookie(true);
cookieManager.AcceptCookie();
cookieManager.Flush(); // Forces cookie sync
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/373472.html
標籤:沙马林 xamarin.forms xamarin-studio
