iPhone: NSHTTPCookie is not saved across app restarts

iPhone: NSHTTPCookie is not saved across app restarts

 

 

In my iPhone app, I want to be able to reuse the same server-side session when my app restarts. A session on the server is identified by a cookie, which is sent on each request. When I restart the app, that cookie is gone and I can't use the same session anymore.

 

What I noticed when I used the NSHTTPCookieStorage to look up the cookie I got from the server, is that [cookie isSessionOnly] returns YES. I get the impression that this is why cookies are not saved across restarts of my app. What would I have to do to make my cookie NOT session only? What HTTP headers do I have to send from the server?

 

 

accepted

You can save the cookie by saving its properties dictionary and then restoring as a new cookiebefore you go to re-connect.

 

Save:

 

NSArray* allCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:URL]];

for (NSHTTPCookie *cookie in allCookies) {

    if ([cookie.name isEqualToString:MY_COOKIE]) { 

        NSMutableDictionary* cookieDictionary = [NSMutableDictionary dictionaryWithDictionary:[[NSUserDefaults standardUserDefaults] dictionaryForKey:PREF_KEY]];

        [cookieDictionary setValue:cookie.properties forKey:URL];

        [[NSUserDefaults standardUserDefaults] setObject:cookieDictionary forKey:PREF_KEY];

    }

 }

Load:

 

NSDictionary* cookieDictionary = [[NSUserDefaults standardUserDefaults] dictionaryForKey:PREF_KEY];

NSDictionary* cookieProperties = [cookieDictionary valueForKey:URL];

if (cookieProperties != nil) {

    NSHTTPCookie* cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];

    NSArray* cookieArray = [NSArray arrayWithObject:cookie];

    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:cookieArray forURL:[NSURL URLWithString:URL] mainDocumentURL:nil];

}

 

 

do you need to synchronize the nsuserdefaults? – Ninja Jan 10 at 8:52

You only need to synchronize if you need to save them right then. Otherwise they will be saved at some interderminate time later. Here's the doc page: developer.apple.com/library/mac/#documentation/Cocoa/Reference/… – Mike Katz Jan 10 at 18:44


你可能感兴趣的:(iPhone)