2011-08-26 141 views
4

在我們的iPhone應用程序中,我們在服務器通信期間使用兩個cookie。一個是短會話cookie(JSESSION),另一個是長會話cookie(REMEMBER ME)。如果答案來自服務器,它會發送一個短會話cookie,我可以在NSHTTPCookieStorage中找到它。NSHTTPCookieStorage和Cookie過期日期

我的問題是這個存儲如何處理cookie的到期日期?因此,如果cookie過期了,它是否會自動刪除該cookie,並且如果我在嘗試從過期的存儲中獲取該cookie的名稱後,是否會收到任何內容?或者我必須手動檢查過期時間嗎?

回答

5

我的問題是這個存儲如何處理cookie的到期日期?

NSHTTPCookieStorage存儲具有到期日期作爲其屬性之一的NSHTTPCookie對象。

http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSHTTPCookie_Class/Reference/Reference.html#//apple_ref/occ/cl/NSHTTPCookie

因此,如果cookie過期,它會自動刪除該cookie,如果我試圖通過它的名字來獲取這個cookie從存儲到期後,我能得到什麼?或者我必須手動檢查過期時間嗎?

您應手動檢查過期和刪除cookie自己

正如在http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSHTTPCookie_Class/Reference/Reference.html#//apple_ref/occ/cl/NSHTTPCookie

The receiver’s expiration date, or nil if there is no specific expiration date such as in the case of 「session-only」 cookies. The expiration date is the date when the cookie should be deleted. 
+0

感謝回答普拉卡什 – madik

4

簡稱更加實用...

+(BOOL) isCookieExpired{ 

    BOOL status = YES; 

    NSArray *oldCookies = [[ NSHTTPCookieStorage sharedHTTPCookieStorage ] 
          cookiesForURL: [NSURL URLWithString:kBASEURL]]; 
    NSHTTPCookie *cookie = [oldCookies lastObject]; 
    if (cookie) { 
     NSDate *expiresDate = [cookie expiresDate]; 
     NSDate *currentDate = [NSDate date]; 
     NSComparisonResult result = [currentDate compare:expiresDate]; 

     if(result==NSOrderedAscending){ 
      status = NO; 
      NSLog(@"expiresDate is in the future"); 
     } 
     else if(result==NSOrderedDescending){ 
      NSLog(@"expiresDate is in the past"); 
     } 
     else{ 
      status = NO; 
      NSLog(@"Both dates are the same"); 
     } 
    } 

    return status; 
}