0

我正在使用ASIFormDataRequest并获取 cookie 作为响应。我试图将它们保存成NSUserDefaults这样:

NSArray * requestCookies = request.responseCookies;
NSArray * requestCookies = request.responseCookies;
if (requestCookies.count) {
    NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject:requestCookies];
    [[NSUserDefaults standardUserDefaults] setObject:cookiesData forKey:kCookies_Key];
    [[NSUserDefaults standardUserDefaults] synchronize];
    NSLog(@"Request cookies: %@", requestCookies);
}
/* output:
Request cookies: (
"<NSHTTPCookie version:0 name:\"name1\" value:\"value1\" expiresDate:(null)
created:2013-02-27 17:49:27 +0000 (3.8368e+08) sessionOnly:TRUE 
domain:\"www.example.com\" path:\"/path\" isSecure:FALSE>",
"<NSHTTPCookie version:0 name:\"name2\" value:\"value2\" expiresDate:(null)
created:2013-02-27 17:49:27 +0000 (3.8368e+08) sessionOnly:TRUE 
domain:\"www.example.com\" path:\"/path\" isSecure:FALSE>"*/

然后我试图恢复这个cookie:

NSData *cookiesData = [[NSUserDefaults standardUserDefaults] objectForKey:kCookies_Key];
if ([cookiesData length]) {
    NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesData];
    NSLog(@"Restored cookies: %@", cookies);
}
/* output:
Restored cookies: (
"<NSHTTPCookie version:0 name:\"name1\" value:\"value1\" expiresDate:(null)
created:2001-01-01 00:00:01 +0000 (1) sessionOnly:TRUE 
domain:\"www.example.com\" path:\"/path\" isSecure:FALSE>",
"<NSHTTPCookie version:0 name:\"name2\" value:\"value2\" expiresDate:(null)
created:2001-01-01 00:00:01 +0000 (1) sessionOnly:TRUE 
domain:\"www.example.com\" path:\"/path\" isSecure:FALSE>"*/

此 cookie 之间的唯一区别是:创建日期。可能我只会将这两个 cookie 的属性保存在 中NSUserDefaults,但为什么我有不同的 cookie 创建日期?

UPD

我尝试仅保存NSHTTPCookie并再次创建此 cookie 的属性,但我的创建日期相同:

created:2001-01-01 00:00:01 +0000 (1)
4

1 回答 1

1

您应该将它们保存在 SharedCookie 存储空间中:

[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]
于 2013-04-17T14:04:57.290 回答