NSHTTPCookie存储和Cookie过期日期

时间:2011-08-26 10:55:36

标签: iphone objective-c nshttpcookie

在我们的iPhone应用程序中,我们在服务器通信期间使用两个cookie。一个是短会话cookie(JSESSION),另一个是长会话cookie(记住我)。如果答案来自服务器,它会发送一个短会话cookie,我可以在NSHTTPCookieStorage中找到它。

我的问题是这个存储如何处理cookie的到期日期?因此,如果cookie过期,它是否会自动删除该cookie,如果我尝试在过期后从存储中获取其名称,那么我能得到任何东西吗?或者我是否必须手动检查到期日期?

2 个答案:

答案 0 :(得分: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.

答案 1 :(得分: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;
}