Ajay shanker
Ajay shanker

Reputation: 65

Cookies in web view xamarin iOS

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);

Upvotes: 3

Views: 3910

Answers (1)

user2468356
user2468356

Reputation:

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. https://learn.microsoft.com/en-us/dotnet/api/foundation.nshttpcookiestorage?view=xamarin-ios-sdk-12

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

Upvotes: 6

Related Questions