Shared instance of NSHTTPCookieStorage does not persist cookies

后端 未结 4 1454
-上瘾入骨i
-上瘾入骨i 2021-02-01 07:48

I\'m developing an application where the server hands me a cookie to identify the user.

My successive requests need to have that cookie to have the response that the use

相关标签:
4条回答
  • 2021-02-01 08:28

    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.

    0 讨论(0)
  • 2021-02-01 08:28

    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.

    0 讨论(0)
  • 2021-02-01 08:29

    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.)

    0 讨论(0)
  • 2021-02-01 08:30

    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.

    0 讨论(0)
提交回复
热议问题