开发者

NSHTTPCookieStorage and Cookie Expiration Date

开发者 https://www.devze.com 2023-03-31 12:53 出处:网络
In our iPhone app we use two cookies during server communication. One is a short session cookie (JSESSION), and the other is a long session cookie (REMEMBER ME). If an answer comes from the server, it

In our iPhone app we use two cookies during server communication. One is a short session cookie (JSESSION), and the other is a long session cookie (REMEMBER ME). If an answer comes from the server, it sends a short session cookie, which I can find in the NSHTTPCookieStorage.

My question is how this storage handles the cookie's expiration date? So if the cookie expires, does it delete that cookie automatically, and if I try to get this cookie by its n开发者_开发百科ame from the storage after expiration, do I get anything? Or do I have to check the expiration manually?


My question is how this storage handles the cookie's expiration date?

NSHTTPCookieStorage stores the NSHTTPCookie objects that has expiration date as one of its property.

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

So if the cookie expires, does it delete that cookie automatically, and if I try to get this cookie by it's name from the storage after expiration, do I get anything? Or do I have to check the expiration manually?

You should check manually for expiration and delete the cookie yourself

As it is referred in 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.


To be more practical...

+(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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号