NSURLRequest doesn't send cookies

Alex Petrov picture Alex Petrov · Mar 30, 2012 · Viewed 8.1k times · Source

I'm developing a newsstand application and use NSURLRequest to download issue assets.

NSArray *contents = [issue.tableOfContents objectForKey:kSNTableOfContentsContents];
NSHTTPCookie *cookie;
NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSLog(@"HERE GO MY COOKIES");
for (cookie in [cookieJar cookies]) {
    NSLog(@"%@", cookie);
}            
for (NSDictionary *contentItem in contents) {
    NSString *contentURL_string = [contentItem objectForKey:kSNTableOfContentsRemoteURL];
    NSURL *contentURL = [NSURL URLWithString:contentURL_string];
    NSString *fileName = [contentItem objectForKey:kSNTableOfContentsContentsURL];      
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:contentURL];
    NKAssetDownload *asset = [newsstandIssue addAssetWithRequest:request];
    [request release];
    ....
    [asset downloadWithDelegate:self];
    ....
}

When the first for loop is executed my cookies appear to be in NSHTTPCookieStorage, but when actual requests are sent, there are no cookie information in headers. I use CharlesProxy to look that up. Could anyone please give some advice what might be causing this issue?

Answer

MrGomez picture MrGomez · Apr 6, 2012

From this thread, the magic incantation appears to be:

NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:
  [cookieJar cookies]];
[request setAllHTTPHeaderFields:headers];

(Warning: untested code.)

This will convert your cookie jar into an array of cookies, then to an NSDictionary of headers, and finally, staple those headers to your request. This is comparable to doing it manually, as Adam Shiemke linked in the question errata, but much cleaner in my opinion.

As per the documentation, you may also want to check HTTPShouldHandleCookies to see if your default cookie policy is being used properly.