Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a cookie for NSURLRequest?

I'm trying to send an authentication string via cookie in a NSMutableURLRequest. I'm trying to create the NSHTTPCookie through

 +(id)cookieWithProperties:(NSDictionary *)properties

But nowhere have I been able to find how to specify the properties other than the simple key-value pair I have for authentication. When I only use my key-value pair, nil is returned.

Any examples, documentation, or thoughts on this would be greatly appreciated.

like image 954
Michael Grinich Avatar asked Mar 27 '09 23:03

Michael Grinich


2 Answers

I noticed on, on my 2.2.1 iPhone, that the cookie didn't get created if NSHTTPCookiePath is not specified, even though it is shown as "optional" in the docs:

So, I do:

NSDictionary *properties = [NSDictionary dictionaryWithObjectsAndKeys:
                            @"example.com", NSHTTPCookieDomain,
                            @"/", NSHTTPCookiePath,  // IMPORTANT!
                            @"testCookies", NSHTTPCookieName,
                            @"1", NSHTTPCookieValue,
                            nil];
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:properties];

NSArray* cookies = [NSArray arrayWithObjects: cookie, nil];

NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];

[request setAllHTTPHeaderFields:headers];
like image 169
jm. Avatar answered Oct 14 '22 23:10

jm.


This is how you set properties in a cookie:

 NSDictionary *properties = [NSDictionary dictionaryWithObjectsAndKeys:
                              url, NSHTTPCookieOriginURL,
                              @"testCookies", NSHTTPCookieName,
                              @"1", NSHTTPCookieValue,
                              nil];
  NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:properties];

In the example above: url, testCookies, and 1 are the values. Likewise, NSHTTPCookieOriginURL, NSHTTPCookieName, NSHTTPCookieValue are the keys for the NSDictionary object, as in key-value pairs.

You set/get properties using NSDictionary and add to NSHTTPCookie.

like image 21
Jordan Avatar answered Oct 14 '22 22:10

Jordan