iPhone manually set Cookies

Hi guys !!! You may have encountered situations where you wish to set some cookies through your app code.
There is a very basic procedure to do it.

1. Create a dictionary with all the cookie properties
2. Create a Cookie passing the property dictionary which you created
3. Set the Cookie using the NSHTTPCookieStorage class

First create a properties dictionary.

NSDictionary *propertiesUsername = [NSDictionary dictionaryWithObjectsAndKeys:
                                        @".yourdomain.com", NSHTTPCookieDomain,
                                        @"cookie_name", NSHTTPCookieName,
                                        @"cookie_value", NSHTTPCookieValue,
                                        @"/", NSHTTPCookiePath,
                                        [[NSDate date] dateByAddingTimeInterval:60*60*24],NSHTTPCookieExpires,
                                        nil];

Most of these are self explanatory. As you can see you have to set the domain, and path in addition to expiry date. I have set it to one day.

The next step is to create the Cookie itself. It can be done using the following method.

NSHTTPCookie *cookieUsername=[[NSHTTPCookie alloc] initWithProperties:propertiesPassword];

Then, get a handle to the NSHTTPCookieStorage and simultaneously set the cookie.

[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookieUsername];

If you want to check whether the Cookie was actually created, you can simply print them using the following code.

NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
   
    for (NSHTTPCookie *cookie in cookies) {
        NSLog(@"----Name: %@ : Value: %@ :Expiration %@ :", cookie.name, cookie.value, cookie.expiresDate);
    }


That's it. Now you can use this method whenever you need to manually set the cookies !!!!

Comments

Popular posts from this blog

Encrypt and Decrypt Images Using Java

Build your own Network sniffer

ASP Response.Write newline