Sunday, June 16, 2013

NSHTTPCookieStorage setCookie example in Objective C (iOS).


NSHTTPCookieStorage setCookie

Stores a specified cookie in the cookie storage if the cookie accept policy permits.

- (void)setCookie:(NSHTTPCookie *)aCookie

Parameters of [NSHTTPCookieStorage setCookie]
aCookie
The cookie to store.

Discussion of [NSHTTPCookieStorage setCookie]
The cookie replaces an existing cookie with the same name, domain, and path, if one exists in the cookie storage. This method accepts the cookie only if the receiver’s cookie accept policy is NSHTTPCookieAcceptPolicyAlways or NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain. The cookie is ignored if the receiver’s cookie accept policy is NSHTTPCookieAcceptPolicyNever.

NSHTTPCookieStorage setCookie example.
// Dictionary of attributes for the new cookie
NSDictionary *newCookieDict = [NSMutableDictionary
                               dictionaryWithObjectsAndKeys:@".example.com", NSHTTPCookieDomain,
                                                            @"Test Cookie", NSHTTPCookieName,
                                                            @"/", NSHTTPCookiePath,
                                                            @"test1234567890", NSHTTPCookieValue,
                                                            @“2011-10-26 00:00:00 -0700", NSHTTPCookieExpires, nil];
// Create a new cookie
NSHTTPCookie *newCookie = [NSHTTPCookie cookieWithProperties:newCookieDict];

// Add the new cookie
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:newCookie];

Example of [NSHTTPCookieStorage setCookie].
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.

NSHTTPCookieStorage setCookie example.
1) Save cookie when they get created by uiwebview.

 NSMutableArray *cookieArray = [[NSMutableArray alloc] init];
    for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
        [cookieArray addObject:cookie.name];
        NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
        [cookieProperties setObject:cookie.name forKey:NSHTTPCookieName];
        [cookieProperties setObject:cookie.value forKey:NSHTTPCookieValue];
        [cookieProperties setObject:cookie.domain forKey:NSHTTPCookieDomain];
        [cookieProperties setObject:cookie.path forKey:NSHTTPCookiePath];
        [cookieProperties setObject:[NSNumber numberWithInt:cookie.version] forKey:NSHTTPCookieVersion];

        [cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires];

        [[NSUserDefaults standardUserDefaults] setValue:cookieProperties forKey:cookie.name];
        [[NSUserDefaults standardUserDefaults] synchronize];

    }

    [[NSUserDefaults standardUserDefaults] setValue:cookieArray forKey:@"cookieArray"];
    [[NSUserDefaults standardUserDefaults] synchronize];
2) Now recreate them as app restarts:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    NSMutableArray* cookieDictionary = [[NSUserDefaults standardUserDefaults] valueForKey:@"cookieArray"];
     NSLog(@"cookie dictionary found is %@",cookieDictionary);

    for (int i=0; i < cookieDictionary.count; i++)
{

        NSLog(@"cookie found is %@",[cookieDictionary objectAtIndex:i]);
        NSMutableDictionary* cookieDictionary1 = [[NSUserDefaults standardUserDefaults] valueForKey:[cookieDictionary objectAtIndex:i]];
        NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieDictionary1];
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];

 }

    // other code

}

End of NSHTTPCookieStorage setCookie example article.