Monday, December 28, 2009

Cookie Management in iPhone

The following code may help people who are looking for some sort of cookie management for their iPhone web application. This post will definitely get you started.

NSURLCredential *userCredentials = [NSURLCredential credentialWithUser:email.text
password:password.text
persistence:NSURLCredentialPersistencePermanent];

NSURLProtectionSpace *space = [[NSURLProtectionSpace alloc] initWithHost:@"localhost"
port:3000
protocol:@"http"
realm:nil
authenticationMethod: NSURLAuthenticationMethodDefault];


[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:userCredentials
forProtectionSpace:space];


After writing the above code, your application will be able to store cookies for the site http://localhost:3000/. You may also change it as per your need and requirement, such as:

* May use three different types of persistence storage for cookies: NSURLCredentialPersistenceNone,
NSURLCredentialPersistenceForSession,
NSURLCredentialPersistencePermanent

* May use different authentications. AuthenticationMethod should be set to one of the values in NSString *NSURLProtectionSpaceHTTPProxy;
NSString *NSURLProtectionSpaceHTTPSProxy;
NSString *NSURLProtectionSpaceFTPProxy;
NSString *NSURLProtectionSpaceSOCKSProxy;

or nil to use the default, NSURLAuthenticationMethodDefault.

For more information, refer to Apple's documentation.