我有一个验证用户的UIWebView.我想启用单点登录.为此,我希望在用户首次通过身份验证时存储Cookie,然后在下次启动应用程序时,Cookie应自动传递到UIWebView并在没有再次输入凭据的情况下对用户进行身份验证.
我正在做类似下面的事情来使用UIWebView
var uri = new Uri(AuthUrl); var nsurl = new NSUrl(uri.GetComponents(UriComponents.HttpRequestUrl, UriFormat.UriEscaped)); wvLogin.LoadRequest(new NSUrlRequest(nsurl));
CookieManager.cs
public static void SaveCookies() { var cookieData = new NSMutableArray (); var cookieStorage = NSHttpCookieStorage.SharedStorage; foreach (var nscookie in cookieStorage.Cookies) { var cookieDictionary = new NSMutableDictionary (); cookieDictionary.Add (NSHttpCookie.KeyName, new NSString (nscookie.Name)); cookieDictionary.Add (NSHttpCookie.KeyValue,new NSString ( nscookie.Value)); cookieDictionary.Add (NSHttpCookie.KeyDomain,new NSString ( nscookie.Domain)); cookieDictionary.Add (NSHttpCookie.KeyPath, new NSString (nscookie.Path)); cookieDictionary.Add (NSHttpCookie.KeySecure, new NSString ( nscookie.IsSecure.ToString())); cookieDictionary.Add (NSHttpCookie.KeyVersion, new NSString (nscookie.Version.ToString())); if (nscookie.ExpiresDate != null) { cookieDictionary.Add (NSHttpCookie.KeyExpires, nscookie.ExpiresDate); } cookieData.Add (cookieDictionary); } cookieData.WriteToFile (StoragePath(), true); } public static string StoragePath() { //var paths = NSSearchPath.GetDirectories (NSSearchPathDirectory.LibraryDirectory, NSUserDomainMask, true); var paths = NSSearchPath.GetDirectories(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomain.User, true); return paths [0].ToString (); } public static void DeleteCookies() { NSHttpCookieStorage cookieStorage = NSHttpCookieStorage.SharedStorage; foreach (var nscookie in cookieStorage.Cookies) { cookieStorage.DeleteCookie(nscookie); } NSUserDefaults.StandardUserDefaults.Synchronize (); } public static void LoadCookies() { var cookies = NSMutableArray.FromFile (StoragePath()); var cookieStorage = NSHttpCookieStorage.SharedStorage; foreach (var nscookie in cookieStorage.Cookies) { cookieStorage.SetCookie(nscookie); } }
LoginScreen.cs
void wvLogin_LoadFinished(object sender, EventArgs e) { int redirectCount = 0; redirect = System.Net.WebUtility.UrlDecode(wvLogin.Request.Url.AbsoluteString); // Do some stuff CookieManager.SaveCookies(); } } else { AppDelegate.Logout(); } } }
我怎样才能做到这一点?感谢任何帮助,因为我是iOS和Xamarin的新手.