2012-03-30 63 views
13

我正在开发一个报刊亭的应用和使用的NSURLRequest下载的问题资产。的NSURLRequest不发送cookie

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]; 
    .... 
} 

当第一个for循环执行了我的饼干似乎是在NSHTTPCookieStorage,但是当实际的请求被发送,也有头无cookie信息。我用CharlesProxy来看看。任何人都可以请提供一些建议可能会导致这个问题?

+0

你可以尝试手动做:http://stackoverflow.com/questions/5954382/ios-is-it-possible-to -set-a-cookie-manually-using-sharedhttpcookiestorage-for-a – 2012-03-30 17:59:58

+0

谢谢,我会试试看。 – 2012-03-30 18:34:52

回答

18

this thread,魔法咒语似乎是:

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

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

这将你的饼干罐转换成饼干的数组,然后头的NSDictionary最后,将这些标题固定到您的要求。这与手动操作相似,正如Adam Shiemke在勘误问题中提到的一样,但在我看来更清晰。

根据the documentation,您可能还想检查HTTPShouldHandleCookies以查看您的默认Cookie政策是否正确使用。

+1

像老板一样工作,但你应该注意到OP必须创建一个NSMutableURLRequest以便能够使用setAllHTTPHeaderFields方法。简单地改变 '的NSURLRequest *请求= [[的NSURLRequest页头] initWithURL:的contentURL]' 到 'NSMutableURLRequest *请求= [[NSMutableURLRequest页头] initWithURL:的contentURL]' – RobP 2014-09-14 17:41:51

+0

也,这似乎是一个很好的机会对于一个类别,人们可以沿着线使用的便捷方法'[myMutableURLRequest addAllCookies]' – RobP 2014-09-14 18:03:46

+0

真棒+1 @MrGomez – mkabatek 2016-06-08 00:14:23

1

在iOS项目中,我发现ASIHTTPRequest对这类问题非常有用的。它做的事情,如身份验证和饼干好得多,内置功能: http://allseeing-i.com/ASIHTTPRequest/

+0

谢谢,我用这个为好,但我不能找到一种方法,使其与书报亭工作工具包。你知道他们是否可以一起工作? – 2012-04-07 16:57:22

+0

不确定,我还没有使用过这个组合。你可能会发现更多的http://allseeing-i.com/ASIHTTPRequest/How-to-use#persistent_cookies – 2012-04-08 07:52:17

+1

ASIHTTPRequest由Ben科普塞是谁写的(2011年最后更新五月)不再支持,他建议不要使用它新项目 – joneswah 2013-01-31 04:03:45