iOS:存储在 session 中过期的 cookie

标签 ios objective-c nshttpcookie nshttpcookiestorage

我必须将 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/

相关文章:

ios - 'default' 对 UITextInputTrait 常量的真正含义是什么

ios - WKHTTPCookieStorage 的 setCookie 在关闭和打开 Web View 后不返回

iphone - NSHTTPCookieStorage 和 Cookie 过期日期

ios - 在 iOS Camera 中实现闪光效果?

ios - 捕获其父 View 框架外的 subview 上的触摸(在多个层上)

不同设备尺寸的 iOS Auto Layout 约束值

c++ - 从 C++ 文件使用 Objective-C++ 文件

ios - 为什么我不能在nsableview单元格中放置nsarray

iphone - 如何将 NSArray 更改为 MKPolyline polylineWithCoordinates 兼容类型?