Cookies in web view xamarin iOS

2019-04-11 20:39发布

问题:

I want to set cookies in web view. Is there any help regarding this?

NSUrl urlq = new NSUrl (url);
webview = new UIWebView ();

webview.LoadRequest(new NSUrlRequest(urlq));
webview.Frame = new RectangleF (0,0, webViewForLoad.Frame.Width, webViewForLoad.Frame.Height);
webview.AllowsInlineMediaPlayback = true;
//webview.LoadRequest (new NSUrl (url, false));
webview.ScalesPageToFit = true;
webViewForLoad.AddSubview (webview);

回答1:

You need to set the cookie in the shared storage. Firstly, set your shared storage policy to always accept your own cookies. This can be placed in your ApplicationDelegate (say ApplicationDidBecomeActive).

NSHttpCookieStorage.SharedStorage.AcceptPolicy = NSHttpCookieAcceptPolicy.Always;

Create your cookie and set it to the shared storage.

var cookieDict = new NSMutableDictionary ();
cookieDict.Add (NSHttpCookie.KeyOriginURL, new NSString("http://example.com"));
cookieDict.Add (NSHttpCookie.KeyName, new NSString("Username"));
cookieDict.Add (NSHttpCookie.KeyValue, new NSString("Batman"));
cookieDict.Add (NSHttpCookie.KeyPath, new NSString("/"));

var myCookie = new NSHttpCookie(cookieDict);

NSHttpCookieStorage.SharedStorage.SetCookie(myCookie);

Any future requests will contain the cookie you have set in the shared storage. So you may want to delete it in the future.

NSHttpCookieStorage.SharedStorage.DeleteCookie(myCookie);

Documentation on NSHTTPCookie and NSHttpCookieStorage:

  1. http://iosapi.xamarin.com/index.aspx?link=T%3AMonoTouch.Foundation.NSHttpCookie

  2. https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSHTTPCookieStorage_Class/index.html