Search code examples
cookiesnsurlsessioncookiestore

How to set cookieAcceptPolicy for ephemeral NSURLSession


I am trying to use ephemeral NSURLSessions to provide separate cookie handling for several tasks within my app. These tasks are not directly bound to a UI. Problem: Whatever I do, the cookieAcceptPolicy of the ephemeral NSHTTPCookieStorage remains NSHTTPCookieAcceptPolicyNever.

Here's my code:

// use a pure in-memory configuration with its own private cache, cookie, and credential store
__block NSURLSessionConfiguration* config = [NSURLSessionConfiguration ephemeralSessionConfiguration];

// do anything to accept all cookies
config.HTTPShouldSetCookies = YES;
config.HTTPCookieAcceptPolicy = NSHTTPCookieAcceptPolicyAlways;
config.HTTPCookieStorage.cookieAcceptPolicy = NSHTTPCookieAcceptPolicyAlways;

__block NSURLSession* session = [NSURLSession sessionWithConfiguration:config];

NSURLSessionDataTask* task = [session dataTaskWithURL:[NSURL URLWithString:@"https://test.cgmlife.com/Catalogs"]
                                    completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                        NSHTTPCookieStorage* cookies = session.configuration.HTTPCookieStorage;
                                        NSLog(@"%@", cookies);
                                        NSLog(@"%lu", cookies.cookieAcceptPolicy);
                                    }];
[task resume];

The output from NSLog is always:

Ephemeral <NSHTTPCookieStorage cookies count:0>
1

where 1 is the value for NSHTTPCookieAcceptPolicyNever (expected 0 for NSHTTPCookieAcceptPolicyAlways). The headers in the response are there.

What can I do to have the NSHTTPCookieStorage remember my cookies while the session is alive? I don't need and don't want any persistence. I just want to keep cookies in memory so that they are reused for further requests in the same session.


Solution

  • It looks like ephemeral sessions don't store cookies ever. eskimo1 says on the devforums:

    ISTR that ephemeral session configurations don't work the way that folks expect based on the documentation. I never got around to looking at this in detail but it seems like you have. You should file a bug about this; the implementation and documentation are clearly out of sync, so one of them needs to be fixed.