我必须将 NSHTTPCookie 设置为 Session。我使用以下代码设置该 cookie 的属性。
NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[cookieProperties setObject:@"mycookiename" forKey:NSHTTPCookieName];
[cookieProperties setObject:@"mycookievalue" forKey:NSHTTPCookieValue];
[cookieProperties setObject:[NSNumber numberWithBool:TRUE] forKey:NSHTTPCookieSecure];
[cookieProperties setObject:@"com.mydomain" forKey:NSHTTPCookieDomain];
[cookieProperties setObject:@"com.mydomain" forKey:NSHTTPCookieOriginURL];
[cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
[cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion];
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
然而,上述两个属性都将到期时间设置为 1 Jan 2001 02:00:00 GMT+2 而不是将到期时间设置为 Session
最佳答案
你应该看看 sessionOnly 属性。 Apple Documentation
它说:
A boolean value that indicates whether the receiver should be discarded at the end of the session (regardless of expiration date). (read-only)
YES if the receiver should be discarded at the end of the session (regardless of expiration date), otherwise NO.
你也可以看看超棒的图书馆ASIHTTPRequest
它有一些很好的方法可以帮助你。来自他们的操作方法:
In this case, ‘session cookies’ refers to ALL cookies created during a session, rather cookies with no expiry date (often referred to as session cookies) that are removed when the application quits.
所以你可能想创建一个没有设置过期日期的NSHTTPCookie
。
此信息也可以在 Apple 文档中找到:
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.
这样做:
NSDictionary *properties = [[[NSMutableDictionary alloc] init] autorelease];
[properties setValue:[@"Test Value" encodedCookieValue] forKey:NSHTTPCookieValue];
[properties setValue:@"ASIHTTPRequestTestCookie" forKey:NSHTTPCookieName];
[properties setValue:@".allseeing-i.com" forKey:NSHTTPCookieDomain];
//Here you can set expiration date
[properties setValue:[NSDate dateWithTimeIntervalSinceNow:60*60] forKey:NSHTTPCookieExpires];
[properties setValue:@"/asi-http-request/tests" forKey:NSHTTPCookiePath];
NSHTTPCookie *cookie = [[[NSHTTPCookie alloc] initWithProperties:properties] autorelease];
关于iOS:存储在 session 中过期的 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27704289/