3

In my iPhone App, to logout my client I need to delete the cookies for a given URL.

It's easy to code and @matt from AFNetworking gave a simple code example to do so.

- (void)cleanCookies
{
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:kBaseURL]];
    for (NSHTTPCookie *cookie in cookies)
    {
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
    }
}

That's the easy bit. Now in my unit tests I would like to prove that my code is deleting the cookies relate to this baseURL.

Question, How do I add a NSHTTPCookie to the NSHTTPCookieStorage so that I can retrieve it with

NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:kBaseURL]];

I am trying to add the cookie like this:

NSMutableDictionary *newCookieDict = [NSMutableDictionary dictionaryWithCapacity:6];
            [newCookieDict setObject:@"cookiie" forKey:NSHTTPCookieName];
            [newCookieDict setObject:@"/api" forKey:NSHTTPCookiePath];
            [newCookieDict setObject:@"2020-10-26 00:00:00 -0700" forKey:NSHTTPCookieExpires];
            [newCookieDict setObject:kSkyStoreBaseURL forKey:NSHTTPCookieOriginURL];
            [newCookieDict setObject:kSkyStoreBaseURL forKey:NSHTTPCookieDomain];
            [newCookieDict setObject:@"value" forKey:NSHTTPCookieValue];

            // Create a new cookie
            NSHTTPCookie *newCookie = [NSHTTPCookie cookieWithProperties:newCookieDict];

            // Add the new cookie
            NSHTTPCookieStorage *cookiesStore = [NSHTTPCookieStorage sharedHTTPCookieStorage];
            [cookiesStore setCookies:@[newCookie] forURL:[NSURL URLWithString:kSkyStoreBaseURL] mainDocumentURL:nil];

The cookie gets added correctly but then I get a nil value when I call it for the specified baseURL!

NSArray *cookies = [cookiesStore cookiesForURL:[NSURL URLWithString:kSkyStoreBaseURL]];

cookies = nil :\

Has anyone been through this before?

Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281

0 Answers0