Search code examples
uiwebviewxamarin.iosnshttpcookie

Set Cookie for UIWebView requests


I want to embed an UIWebView into my MonoTouch application for an area that is not yet implemented natively.

In order to authenticate with the website I want to set a cookie containing a key for the current session.

I tried creating a NSDictionary with the properties for the Cookie and then create a new NSHttpCookie and add it to the NSHttpCookieStorage.SharedStorage.

Sadly the cookie seems to be empty and not used for the request.

An example of how to build be cookie with properties and a comment on whether or not this is the simplest way to do this would be greatly appreciated.


Solution

  • Whenever I need to send cookies and params up to the server I use something like RestSharp or Hammock and then pass the response.Content value into UIWebView's loadHtmlString method:

    //setup cookies and params here
    var response = client.Execute(req);
    _webView = new UIWebView();
    _webView.LoadHtmlString(response.Content, new NSUrl(baseUrl));
    

    The NSDictionary API is fairly trivial too:

    var props = new NSMutableDictionary ();
    props.Add (NSHttpCookie.KeyOriginURL, new
    NSString("http://yodawg.com"));
    props.Add (NSHttpCookie.KeyName, new NSString("iherd"));
    props.Add (NSHttpCookie.KeyValue, new NSString("ulikecookies"));
    props.Add (NSHttpCookie.KeyPath, new NSString("/"));