views:

2995

answers:

3

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.

+3  A: 

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, and NSHTTPCookieOriginURL, NSHTTPCookieName, NSHTTPCookieValue are the Keys for the NSDictionary object. You set/get properties using NSDictionary and add to NSHTTPCookie.

Cheers, Jordan

Jordan
Actually i was not able to get it work, only with NSHTTPCookieDomain, and NSHTTPCookiePath. See jm's answer. Also: http://lists.apple.com/archives/Webkitsdk-dev/2003/Sep/msg00003.html
mfazekas
+3  A: 

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:
                            @"domain.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];
jm
+1  A: 

I could not get that to work.

I got this to work however:

NSMutableURLRequest* ret = [NSMutableURLRequest requestWithURL:myURL]; [ret setValue:[NSString stringWithFormat:@"myCookie=foobar", forHTTPHeaderField:@"Cookie"];