Sunday, June 16, 2013

NSHTTPCookieStorage NSHTTPCookieAcceptPolicyAlways example in Objective C (iOS).


NSHTTPCookieStorage NSHTTPCookieAcceptPolicyAlways

NSHTTPCookieAcceptPolicy
NSHTTPCookieAcceptPolicy specifies the cookie acceptance policies implemented by the NSHTTPCookieStorage class.

typedef enum {
NSHTTPCookieAcceptPolicyAlways,
NSHTTPCookieAcceptPolicyNever,
NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain
} NSHTTPCookieAcceptPolicy;

Constants
NSHTTPCookieAcceptPolicyAlways
Accept all cookies. This is the default cookie accept policy.
NSHTTPCookieAcceptPolicyNever
Reject all cookies.
NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain
Accept cookies only from the main document domain.

NSHTTPCookieStorage NSHTTPCookieAcceptPolicyAlways 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 NSHTTPCookieAcceptPolicyAlways].
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];

    NSHTTPCookie *cookie;
    for (cookie in [NSHTTPCookieStorage sharedHTTPCookieStorage].cookies) {
        NSLog(@"%@=%@", cookie.name, cookie.value);
    }

NSHTTPCookieStorage NSHTTPCookieAcceptPolicyAlways example.
You might want to check

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

End of NSHTTPCookieStorage NSHTTPCookieAcceptPolicyAlways example article.