8

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

我的问题是这个存储如何处理 cookie 的到期日期?因此,如果 cookie 过期,它是否会自动删除该 cookie,并且如果我在过期后尝试通过其名称从存储中获取此 cookie,我会得到什么吗?还是我必须手动检查到期时间?

4

2 回答 2

9

我的问题是这个存储如何处理 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.
于 2011-08-26T19:37:39.510 回答
5

为了更实用...

+(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;
}
于 2013-09-01T20:50:03.420 回答