2012-03-30 66 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