9

In: This Question it is said AFNetworking takes care of cookies automatically in the background, but in a Previous question I asked, I was having trouble keeping the session on the server that was made in php when I logged in. Once I closed(stop debugging in Xcode) the app and went back in the session was gone. The answer was to persist cookies like so to fix the problem:

NSData *cookiesData = [[NSUserDefaults standardUserDefaults] objectForKey:@"User"];
if ([cookiesData length] > 0) {
     for (NSHTTPCookie *cookie in [NSKeyedUnarchiver cookiesData]) {
           [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
      }
}

This gives me an app crash when I try to do something like this. When I log in I set the NSUserDefault like so:

[[NSUserDefaults standardUserDefaults] setObject:data forKey:@"User"];
//Then synthesize

Is this the wrong way to use this? Is NSHTTPCookieStorage even my problem? Thanks.

Community
  • 1
  • 1
TMan
  • 3,916
  • 17
  • 57
  • 113

1 Answers1

37

Use the following, this is a correct way to save and load cookies that is working for me:

- (void)saveCookies{

    NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject: [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject: cookiesData forKey: @"sessionCookies"];
    [defaults synchronize];

}

- (void)loadCookies{

    NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData: [[NSUserDefaults standardUserDefaults] objectForKey: @"sessionCookies"]];
    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];

    for (NSHTTPCookie *cookie in cookies){
        [cookieStorage setCookie: cookie];
    }

}

Hope it helps!

clopez
  • 4,294
  • 3
  • 25
  • 41
  • 1
    Bear in mind storing session cookies in `NSUserDefaults` is a terrible idea because it is stored unencrypted in the app sandbox. Consider using Keychain instead – jackslash May 02 '14 at 11:25
  • 1
    It seems about as secure as storing them in a web browser... Or am I missing something? – Gazzini Mar 13 '15 at 03:45
  • For some reason I can't get this to work. It causes a crash even though the cookies when analyzed in [self loadCookies] appear valid. 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndexedSubscript:]: unrecognized selector sent to instance – George L Apr 13 '15 at 22:49