Shared instance of NSHTTPCookieStorage does not persist cookies

不羁的心 提交于 2019-12-02 19:26:07

NSHttpCookieStorage loses its cookies because you didn't set the expiration time for cookies. Setting expiration time is necessary otherwise your cookies will lose when your app exits.

Here is a quick look how I stored my cookies during app exit and launch,

NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[cookieProperties setObject:name forKey:NSHTTPCookieName];
[cookieProperties setObject:strValue forKey:NSHTTPCookieValue];
[cookieProperties setObject:@"myserver.com" forKey:NSHTTPCookieDomain];    // Without http://
[cookieProperties setObject:@"myserver.com" forKey:NSHTTPCookieOriginURL]; // Without http://
[cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];

// set expiration to one month from now or any future NSDate of your choice
// this makes the cookie sessionless and it will persist across web sessions and app launches
/// if you want the cookie to be destroyed when your app exits, don't set this
[cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires];

NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];

Hope this helps.

Is this the simulator? And using rolling cookies?

In the simulator, cookies don't really persist as they should, because they're shared with desktop Safari. As the cookies roll over, one eventually overwrites the other.

This isn't a problem on the device itself, where each app has its own cookie store. (And, truth be told, I haven't noticed it happening yet in Mountain Lion.)

deleted_user

humayun might be right -

However you should not be writing cookies to NSUserDefaults -

The whole point of the sharedHTTPCookieStorage is you read them from there.

NSArray *httpCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:httpUrl];

You should not even be able to write those cookies to NSUserDefaults for security reasons. But maybe you can. Either way its probable that the timeout wasnt set as humayun mentioned.

Either way please refactor your code and dont try to store cookies in user prefs.

Solved !

After some simple debugging I found out that the problem was with the url I was using in cookiesForURL:. I simply started using cookies property and now it works fine.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!