Search code examples
iosnsurlsessionnshttpcookienshttpurlresponsenshttpcookiestorage

NSHTTPCookieStorage for same URL but different users


May be this is a dumb question, but I want to store cookies for same url but different for usernames. How can this be achieved using NSHTTPCookieStorage ? This is how I store cookies from response.

        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;

        NSDictionary *headerFields = [httpResponse allHeaderFields];


        NSArray* cookies = [NSHTTPCookie
                            cookiesWithResponseHeaderFields:headerFields
                            forURL:[NSURL URLWithString:@""]];

        for (NSHTTPCookie *cookie in cookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }

       NSString *urlString = ...;

        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:cookies forURL:[NSURL URLWithString:urlString] mainDocumentURL:nil];

Solution

  • If I understand you correctly, you want to have separate sets of cookies for different users. If so, then you should:

    1. Create your own custom cookie storage class (probably just a dictionary with the base URL as the key and an array of cookies as the value) and store cookies there in addition to using the sharedHTTPCookieStorage object.

    2. When you change users, wipe the shared cookie storage and copy the cookies from the new user's cookie jar (or selectively remove every cookie created by that user from the shared jar).

    If I misunderstood you and you want to store one particular cookie outside of the shared cookie storage for some reason:

    1. Create an NSURLSession object based on a configuration with a nil cookie jar (disabling automatic cookie storage).

    2. Store the cookies into a cookie jar like you're doing above (which may or may not be the shared cookie jar), but leave out the ones you want to avoid storing.

    3. Write a method to adds the cookies from that cookie jar to an NSURLRequest object.

    4. Always remember to call that method on your URL request objects before you create tasks with them.

    This all assumes NSURLSession, of course. I don't think there's a way to control cookie storage with NSURLConnection. All cookies get stored in the cookie jar, period, AFAIK.