Shared instance of NSHTTPCookieStorage does not persist cookies

后端 未结 4 1463
-上瘾入骨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.

提交回复
热议问题