iOS engineer who likes clean, simple designs and sans-serif.


Cookies with AFNetworking in iOS7

Recently, I had to hit a stateful internal API and needed to store an user authentication cookie.
I couldn’t figure out how to do this in the AFNetworking documentation, but I found a simple answer in this stackoverflow post.

The code:

- (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];


For me, I just did [self saveCookies] after successful user authentication and then [self loadCookies] when I needed to perform GET and POST operations. Hope this helps!

Leave a Comment