Setting cookie in NSHTTPCookieStorage

7.7k views Asked by At

I am trying to take a cookie from NSHTTPCookieStorage and use it for another URL within my App. I am copying a cookie from NSHTTPCookieStorage and then setting the cookie for a different URL in NSHTTPCookieStorage using the copied cookie. I am trying to following code however when I print out the cookies for the other URL there are none.

    // authCookie is a cookie already in NSHTTPCookieStorage.
    NSURL *searchURL = [NSURL URLWithString:searchURLString];
    NSDictionary *authCookieProperties = [[[authCookie properties] copy] autorelease];
    NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionaryWithDictionary:authCookieProperties];

    [cookieProperties setObject:searchURL forKey:NSHTTPCookieDomain];
    [cookieProperties setObject:searchURL forKey:NSHTTPCookieOriginURL];
    NSHTTPCookie *searchCookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
    [sharedHTTPCookieStorage setCookie:searchCookie];
    [sharedHTTPCookieStorage setCookies:[NSArray arrayWithObject:searchCookie] 
                                 forURL:searchURL 
                        mainDocumentURL:nil];

    NSLog(@"Cookies for search = %@", [sharedHTTPCookieStorage cookiesForURL:searchURL]);
    NSLog(@"All Cookies = ");
    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *cookie in [cookieJar cookies]) {
        NSLog(@"%@", cookie);
    }
    /*
    Console Output (With URL and cookie values hidden):
    Cookies for search = ()
    All Cookies = 
    <NSHTTPCookie version:0 name:"auth_token" value:"COOKIEVALUE" expiresDate:(null) created:2001-01-01 00:00:01 +0000 (1) sessionOnly:TRUE domain:"<search_url>" path:"/" isSecure:FALSE>
    <NSHTTPCookie version:0 name:"auth_token" value:"COOKIEVALUE" expiresDate:(null) created:2012-05-14 17:59:36 +0000 (3.58711e+08) sessionOnly:TRUE domain:"<URL_of_auth_cookie>" path:"/" isSecure:FALSE>
    */
1

There are 1 answers

0
Farrukh Javeid On BEST ANSWER

You have to keep tab if the values that you are providing in the new cookie are good enough because as per the Apple reference, it is supposed to return nil if the initializing values are invalid in any particular way. You can further check this out at this link here. It has a rather nice way of creating a cookie from scratch!