Showing posts with label NSHTTPCookieStorage example. Show all posts
Showing posts with label NSHTTPCookieStorage example. Show all posts

Sunday, June 16, 2013

NSHTTPCookieStorage setCookies example in Objective C (iOS).


NSHTTPCookieStorage setCookies

Adds an array of cookies to the receiver if the receiver’s cookie acceptance policy permits.

- (void)setCookies:(NSArray *)cookies forURL:(NSURL *)theURL mainDocumentURL:(NSURL *)mainDocumentURL

Parameters of [NSHTTPCookieStorage setCookies]
cookies
The cookies to add.
theURL
The URL associated with the added cookies.
mainDocumentURL
The URL of the main HTML document for the top-level frame, if known. Can be nil. This URL is used to determine if the cookie should be accepted if the cookie accept policy is NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain.

Discussion of [NSHTTPCookieStorage setCookies]
The cookies will replace existing cookies with the same name, domain, and path, if one exists in the cookie storage. The cookie will be ignored if the receiver's cookie accept policy is NSHTTPCookieAcceptPolicyNever.

To store cookies from a set of response headers, an application can use cookiesWithResponseHeaderFields:forURL: passing a header field dictionary and then use this method to store the resulting cookies in accordance with the receiver’s cookie acceptance policy.

NSHTTPCookieStorage setCookies example.
- ( void )connection: (NSURLConnection *)connection
          didReceiveResponse: (NSURLResponse *)response
{
    NSHTTPURLResponse        *httpResponse = (NSHTTPURLResponse *)response;
    NSArray                  *cookies;

    cookies = [ NSHTTPCookie cookiesWithResponseHeaderFields:
                             [ httpResponse allHeaderFields ]];
    [[ NSHTTPCookieStorage sharedHTTPCookieStorage ]
            setCookies: cookies forURL: self.url mainDocumentURL: nil ];
}

Example of [NSHTTPCookieStorage setCookies].
    NSHTTPURLResponse   * response;
    NSError             * error;
    NSMutableURLRequest * request;
    request = [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://temp/gomh/authenticate.py?setCookie=1"]
                                            cachePolicy:NSURLRequestReloadIgnoringCacheData
                                        timeoutInterval:60] autorelease];

    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
    NSLog(@"RESPONSE HEADERS: \n%@", [response allHeaderFields]);

    // If you want to get all of the cookies:
    NSArray * all = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[NSURL URLWithString:@"http://temp"]];
    NSLog(@"How many Cookies: %d", all.count);
    // Store the cookies:
    // NSHTTPCookieStorage is a Singleton.
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:all forURL:[NSURL URLWithString:@"http://temp"] mainDocumentURL:nil];

    // Now we can print all of the cookies we have:
    for (NSHTTPCookie *cookie in all)
        NSLog(@"Name: %@ : Value: %@, Expires: %@", cookie.name, cookie.value, cookie.expiresDate);

    // Now lets go back the other way.  We want the server to know we have some cookies available:
    // this availableCookies array is going to be the same as the 'all' array above.  We could
    // have just used the 'all' array, but this shows you how to get the cookies back from the singleton.
    NSArray * availableCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:@"http://temp"]];
    NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:availableCookies];

    // we are just recycling the original request
    [request setAllHTTPHeaderFields:headers];

    request.URL = [NSURL URLWithString:@"http://temp/gomh/authenticate.py"];
    error       = nil;
    response    = nil;

    NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSLog(@"The server saw:\n%@", [[[NSString alloc] initWithData:data encoding: NSASCIIStringEncoding] autorelease]);

NSHTTPCookieStorage setCookies example.
Save:

NSArray* allCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:URL]];
for (NSHTTPCookie *cookie in allCookies) {
    if ([cookie.name isEqualToString:MY_COOKIE]) {
        NSMutableDictionary* cookieDictionary = [NSMutableDictionary dictionaryWithDictionary:[[NSUserDefaults standardUserDefaults] dictionaryForKey:PREF_KEY]];
        [cookieDictionary setValue:cookie.properties forKey:URL];
        [[NSUserDefaults standardUserDefaults] setObject:cookieDictionary forKey:PREF_KEY];
    }
 }
Load:

NSDictionary* cookieDictionary = [[NSUserDefaults standardUserDefaults] dictionaryForKey:PREF_KEY];
NSDictionary* cookieProperties = [cookieDictionary valueForKey:URL];
if (cookieProperties != nil) {
    NSHTTPCookie* cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
    NSArray* cookieArray = [NSArray arrayWithObject:cookie];
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:cookieArray forURL:[NSURL URLWithString:URL] mainDocumentURL:nil];
}

End of NSHTTPCookieStorage setCookies example article.

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.

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.

NSHTTPCookieStorage deleteCookie example in Objective C (iOS).


NSHTTPCookieStorage deleteCookie

Deletes the specified cookie from the cookie storage.

- (void)deleteCookie:(NSHTTPCookie *)aCookie

Parameters of [NSHTTPCookieStorage deleteCookie]
aCookie
The cookie to delete.

NSHTTPCookieStorage deleteCookie example.
NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
        NSArray* facebookCookies = [cookies cookiesForURL:
                                    [NSURL URLWithString:@"http://login.facebook.com"]];
        for (NSHTTPCookie* cookie in facebookCookies) {
            [cookies deleteCookie:cookie];
        }

Example of [NSHTTPCookieStorage deleteCookie].
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *each in cookieStorage.cookies) {
        [cookieStorage deleteCookie:each];
    }

NSHTTPCookieStorage deleteCookie example.
NSArray *newCookie = [NSArray arrayWithArray:[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]];

for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
}
for (NSHTTPCookie *cookie in newCookie) {
    NSMutableDictionary *properties = [NSMutableDictionary dictionaryWithDictionary:cookie.properties];
    [properties removeObjectForKey:NSHTTPCookieExpires];
     NSHTTPCookie *changeCookie = [NSHTTPCookie cookieWithProperties:properties];
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:changeCookie];

End of NSHTTPCookieStorage deleteCookie example article.

NSHTTPCookieStorage cookiesForURL example in Objective C (iOS).


NSHTTPCookieStorage cookiesForURL

Returns all the cookie storage’s cookies that are sent to a specified URL.

- (NSArray *)cookiesForURL:(NSURL *)theURL

Parameters of [NSHTTPCookieStorage cookiesForURL]
theURL
The URL to filter on.

Return Value
An array of cookies whose URL matches the provided URL.

Discussion of [NSHTTPCookieStorage cookiesForURL]
An application can use NSHTTPCookie method requestHeaderFieldsWithCookies: to turn this array into a set of header fields to add to an NSMutableURLRequest object.

NSHTTPCookieStorage cookiesForURL example.
first check if

[[NSHTTPCookieStorage sharedHTTPCookieStorage]
    cookiesForURL:[NSURL URLWithString:theCookie]]
returns what you think it should return. If not, take a closer look at the value of theCookie.

Example of [NSHTTPCookieStorage cookiesForURL].
- ( void )reloadWebview: (id)sender
{
    NSArray                 *cookies;
    NSDictionary            *cookieHeaders;
    NSMutableURLRequest     *request;

    cookies = [[ NSHTTPCookieStorage sharedHTTPCookieStorage ]
                cookiesForURL: self.url ];
    if ( !cookies ) {
        /* kick off new NSURLConnection to retrieve new auth cookie */
        return;
    }

    cookieHeaders = [ NSHTTPCookie requestHeaderFieldsWithCookies: cookies ];
    request = [[ NSMutableURLRequest alloc ] initWithURL: self.url ];
    [ request setValue: [ cookieHeaders objectForKey: @"Cookie" ]
              forHTTPHeaderField: @"Cookie" ];

    [ self.webView loadRequest: request ];
    [ request release ];
}

NSHTTPCookieStorage cookiesForURL example.
    NSHTTPURLResponse   * response;
    NSError             * error;
    NSMutableURLRequest * request;
    request = [[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://temp/gomh/authenticate.py?setCookie=1"]
                                            cachePolicy:NSURLRequestReloadIgnoringCacheData
                                        timeoutInterval:60] autorelease];

    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
    NSLog(@"RESPONSE HEADERS: \n%@", [response allHeaderFields]);

    // If you want to get all of the cookies:
    NSArray * all = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[NSURL URLWithString:@"http://temp"]];
    NSLog(@"How many Cookies: %d", all.count);
    // Store the cookies:
    // NSHTTPCookieStorage is a Singleton.
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:all forURL:[NSURL URLWithString:@"http://temp"] mainDocumentURL:nil];

    // Now we can print all of the cookies we have:
    for (NSHTTPCookie *cookie in all)
        NSLog(@"Name: %@ : Value: %@, Expires: %@", cookie.name, cookie.value, cookie.expiresDate);

    // Now lets go back the other way.  We want the server to know we have some cookies available:
    // this availableCookies array is going to be the same as the 'all' array above.  We could
    // have just used the 'all' array, but this shows you how to get the cookies back from the singleton.
    NSArray * availableCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:@"http://temp"]];
    NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:availableCookies];

    // we are just recycling the original request
    [request setAllHTTPHeaderFields:headers];

    request.URL = [NSURL URLWithString:@"http://temp/gomh/authenticate.py"];
    error       = nil;
    response    = nil;

    NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSLog(@"The server saw:\n%@", [[[NSString alloc] initWithData:data encoding: NSASCIIStringEncoding] autorelease]);

End of NSHTTPCookieStorage cookiesForURL example article.

NSHTTPCookieStorage cookies example in Objective C (iOS).


NSHTTPCookieStorage cookies

Returns the cookie storage’s cookies.

- (NSArray *)cookies

Return Value
An array containing all of the cookie storage’s cookies.

Availability
Available in iOS 2.0 and later.

Discussion of [NSHTTPCookieStorage cookies]
If you want to sort the cookie storage’s cookies, you should use the sortedCookiesUsingDescriptors: method instead of sorting the result of this method.

NSHTTPCookieStorage cookies example.
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *each in cookieStorage.cookies) {
        [cookieStorage deleteCookie:each];
    }

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

End of NSHTTPCookieStorage cookies example article.

NSHTTPCookieStorage sharedHTTPCookieStorage example in Objective C (iOS).


NSHTTPCookieStorage sharedHTTPCookieStorage

Returns the shared cookie storage instance.

+ (NSHTTPCookieStorage *)sharedHTTPCookieStorage

Return Value of [NSHTTPCookieStorage sharedHTTPCookieStorage]
The shared cookie storage instance.
NSHTTPCookieStorage sharedHTTPCookieStorage example.
NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[cookieProperties setObject:name forKey:NSHTTPCookieName];
[cookieProperties setObject:strValue forKey:NSHTTPCookieValue];
[cookieProperties setObject:@"myserver.com" forKey:NSHTTPCookieDomain];    // Without http://
[cookieProperties setObject:@"myserver.com" forKey:NSHTTPCookieOriginURL]; // Without http://
[cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];

// 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];

Example of [NSHTTPCookieStorage sharedHTTPCookieStorage].
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *each in cookieStorage.cookies) {
        [cookieStorage deleteCookie:each];
    }

NSHTTPCookieStorage sharedHTTPCookieStorage 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 sharedHTTPCookieStorage example article.