Sunday, June 16, 2013

NSHTTPCookieStorage setCookieAcceptPolicy example in Objective C (iOS).


NSHTTPCookieStorage setCookieAcceptPolicy

Sets the cookie accept policy of the cookie storage.

- (void)setCookieAcceptPolicy:(NSHTTPCookieAcceptPolicy)aPolicy

Parameters of [NSHTTPCookieStorage setCookieAcceptPolicy]
aPolicy
The new cookie accept policy.

Discussion of [NSHTTPCookieStorage setCookieAcceptPolicy]
The default cookie accept policy is NSHTTPCookieAcceptPolicyAlways. Changing the cookie policy affects all currently running applications using the cookie storage.

NSHTTPCookieStorage setCookieAcceptPolicy example.
First, in applicationDidBecomeActive add this line

[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
The cookieAcceptPolicy is shared across apps and can be changed without your knowledge, so you want to be sure you have the accept policy you need every time your app is running.

Then, to set the cookie:

NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[cookieProperties setObject:@"testCookie" forKey:NSHTTPCookieName];
[cookieProperties setObject:@"someValue123456" forKey:NSHTTPCookieValue];
[cookieProperties setObject:@"www.example.com" forKey:NSHTTPCookieDomain];
[cookieProperties setObject:@"www.example.com" forKey:NSHTTPCookieOriginURL];
[cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
[cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion];

// set expiration to one month from now or any NSDate of your choosing
// this makes the cookie sessionless and it will persist across web sessions and app launches
/// if you want the cookie to be destroyed when your app exits, don't set this
[cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires];

NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
This cookie has the name testCookie and value someValue123456 and will be sent with any http request to www.example.com.

Example of [NSHTTPCookieStorage setCookieAcceptPolicy].
Try changing the cookie acceptance policy instead:

[NSHTTPCookieStorage setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyNever];

NSHTTPCookieStorage setCookieAcceptPolicy example.
You might want to check

if ([[NSHTTPCookieStorage sharedHTTPCookieStorage] cookieAcceptPolicy] != NSHTTPCookieAcceptPolicyAlways) {
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];      
}

End of NSHTTPCookieStorage setCookieAcceptPolicy example article.