NSURLRequest不发送cookie

Ale*_*rov 13 cocoa cocoa-touch objective-c ios newsstand-kit

我正在开发报摊应用程序并使用NSURLRequest下载问题资产.

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];
    ....
}
Run Code Online (Sandbox Code Playgroud)

执行第一个for循环时,我的cookie似乎在NSHTTPCookieStorage中,但是当发送实际请求时,标头中没有cookie信息.我使用CharlesProxy来查看它.有谁可以请一些可能导致这个问题的建议?

MrG*_*mez 18

这个线程,神奇的咒语似乎是:

NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:
  [cookieJar cookies]];
[request setAllHTTPHeaderFields:headers];
Run Code Online (Sandbox Code Playgroud)

(警告:未经测试的代码.)

这会将您的cookie jar转换为一组cookie,然后转换为一个NSDictionary标题,最后将这些标题装订到您的请求中.这与手动操作相当,正如Adam Shiemke在问题勘误表中所述,但在我看来更加清晰.

根据文档,您可能还需要检查HTTPShouldHandleCookies您的默认cookie策略是否正确使用.