当前位置:  开发笔记 > 编程语言 > 正文

维护Cookies UIWebView iOS Xamarin

如何解决《维护CookiesUIWebViewiOSXamarin》经验,为你挑选了0个好方法。

我有一个验证用户的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的新手.

推荐阅读
可爱的天使keven_464
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有