iOS: Storing cookie that expires on session

5.8k views Asked by At

I have to set NSHTTPCookie such that it expiry is set to Session. I used the following code to set properties of that cookie.

NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];

[cookieProperties setObject:@"mycookiename" forKey:NSHTTPCookieName];
[cookieProperties setObject:@"mycookievalue" forKey:NSHTTPCookieValue];
[cookieProperties setObject:[NSNumber numberWithBool:TRUE] forKey:NSHTTPCookieSecure];
[cookieProperties setObject:@"com.mydomain" forKey:NSHTTPCookieDomain];
[cookieProperties setObject:@"com.mydomain" forKey:NSHTTPCookieOriginURL];
[cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
[cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion];

NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];

However both of the above properties set the expiry to 1 Jan 2001 02:00:00 GMT+2 rather than setting the expiry to Session

1

There are 1 answers

5
dehlen On

You should have a look at sessionOnly property. Apple Documentation

It says:

A boolean value that indicates whether the receiver should be discarded at the end of the session (regardless of expiration date). (read-only)

YES if the receiver should be discarded at the end of the session (regardless of expiration date), otherwise NO.

You can also have a look at the superb library ASIHTTPRequest

It has some nice methods that can help you. From their How-To:

In this case, ‘session cookies’ refers to ALL cookies created during a session, rather cookies with no expiry date (often referred to as session cookies) that are removed when the application quits.

So you might want to create a NSHTTPCookie with no expiration date set.

This information can also be found in the Apple Docs:

The receiver’s expiration date, or nil if there is no specific expiration date such as in the case of “session-only” cookies. The expiration date is the date when the cookie should be deleted.

To do so:

NSDictionary *properties = [[[NSMutableDictionary alloc] init] autorelease];
[properties setValue:[@"Test Value" encodedCookieValue] forKey:NSHTTPCookieValue];
[properties setValue:@"ASIHTTPRequestTestCookie" forKey:NSHTTPCookieName];
[properties setValue:@".allseeing-i.com" forKey:NSHTTPCookieDomain];

//Here you can set expiration date
[properties setValue:[NSDate dateWithTimeIntervalSinceNow:60*60] forKey:NSHTTPCookieExpires];      
[properties setValue:@"/asi-http-request/tests" forKey:NSHTTPCookiePath];
NSHTTPCookie *cookie = [[[NSHTTPCookie alloc] initWithProperties:properties] autorelease];