Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSURLRequest doesn't send cookies

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?

like image 860
Alex Petrov Avatar asked Mar 30 '12 16:03

Alex Petrov


2 Answers

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.

like image 86
MrGomez Avatar answered Sep 25 '22 01:09

MrGomez


On iOS projects I found the ASIHTTPRequest very useful for this kind of problems. It does things like authentication and cookies a lot better that the build-in functions: http://allseeing-i.com/ASIHTTPRequest/

like image 31
Collin Kleine Avatar answered Sep 23 '22 01:09

Collin Kleine