Wednesday, June 12, 2013

NSHTTPCookie cookiesWithResponseHeaderFields forURL example in Objective C (iOS).

NSHTTPCookie cookiesWithResponseHeaderFields forURL

Returns an array of NSHTTPCookie objects corresponding to the provided response header fields for the provided URL.

+ (NSArray *)cookiesWithResponseHeaderFields:(NSDictionary *)headerFields forURL:(NSURL *)theURL

Parameters of [NSHTTPCookie cookiesWithResponseHeaderFields forURL]
The header fields used to create the NSHTTPCookie objects.
The URL associated with the created cookies.

Return Value
The array of created cookies.

Discussion of [NSHTTPCookie cookiesWithResponseHeaderFields forURL]
This method ignores irrelevant header fields in headerFields, allowing dictionaries to contain additional data.

If headerFields does not specify a domain for a given cookie, the cookie is created with a default domain value of theURL.

If headerFields does not specify a path for a given cookie, the cookie is created with a default path value of “/”.

NSHTTPCookie cookiesWithResponseHeaderFields forURL example.
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSHTTPURLResponse *)response {
    NSURL* redirected_url = [request URL];
    NSString* querystr = [redirected_url absoluteString];

    if (response != nil) {
        NSArray* zzzz = [NSHTTPCookie
                         cookiesWithResponseHeaderFields:[response allHeaderFields]
                         forURL:[NSURL URLWithString:@""]];

        if ([zzzz count] > 0) {
            if ([querystr isEqualToString:@""]) {
                NSMutableArray* actualCookies = [[NSMutableArray alloc] init];
                NSUInteger i, count = [zzzz count];
                for (i = 0; i < count; i++) {
                    NSHTTPCookie* xxx = [zzzz objectAtIndex:i];
                    [actualCookies addObject:xxx];

                NSHTTPCookie* obj = [self.tmpCookies objectAtIndex:0];
                [actualCookies addObject:obj];

                NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:actualCookies];

                NSURL *url = [NSURL URLWithString:@""];
                NSMutableURLRequest* xrequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

                [xrequest setHTTPMethod:@"GET"];
                [xrequest setAllHTTPHeaderFields:headers];
                [xrequest setValue:@"" forHTTPHeaderField: @"Referer"];

                [viewController setAuthCookieAfterValidLogin:zzzz];

                return xrequest;

    return request;

Example of [NSHTTPCookie cookiesWithResponseHeaderFields forURL].
- ( 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 ];

NSHTTPCookie cookiesWithResponseHeaderFields forURL example.
Assuming you have an NSHTTPURLResponse, you can get an array of cookies like so:

NSDictionary * headers = [(NSHTTPURLResponse *)response allHeaderFields];
NSArray * cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:headers forURL:response.URL];
Where response is the NSHTTPURLResponse.

You're going to get NSURLResponses in these 2 methods of the NSURLConnectionDelegate

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse;
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
NSHTTPCookie has a properties property which returns an NSDictionary, so you can save them. They can then be created with the same dictionary using -initWithProperties:

To send them, you'll need to create your own string for the Cookie header of a NSURLRequest. Something like:

NSMutableString * cookieString = [[NSMutableString alloc] init];
for (NSHTTPCookie * cookie in myLoadedCookies){
    [cookieString appendFormat:@"%@=%@; ",, cookie.value];
[request setValue:cookieString forHTTPHeaderField:@"Cookie"];
[cookieString release];
Where request is an NSMutableURLRequest.

You should also make sure to stop iOS managing cookies itself:

[request setHTTPShouldHandleCookies:NO];

End of NSHTTPCookie cookiesWithResponseHeaderFields forURL example article.