Persisting Cookies In An iOS Application?

Cocoa TouchIos

Cocoa Touch Problem Overview


I am going to use NSHTTPCookieStorage in an iOS App to manage cookies that are retrieved from a url, and I understand that it will manage cookies during your application's runtime. However, I was wondering if it's possible to persist cookies after the application has closed. And then read those cookies again when the app is opened again. Does NSHTTPCookieStorage persist cookies between app uses? Or just during the applications runtime? Do I need to use CoreData to persist these cookies?`

Cocoa Touch Solutions


Solution 1 - Cocoa Touch

You shouldn't need to persist the cookies yourself as suggested in the other answer. NSHTTPCookieStorage will persist the cookies for you but you need to ensure that the cookies have an expiry date set on the server-side.

Cookies without an expiry date are considered 'session only' and will get cleared when you restart the app. You can check the 'session only' situation via a BOOL property in NSHTTPCookie. This is standard cookie stuff and not something specific to iOS.

Solution 2 - Cocoa Touch

You need to re-set the cookies when your app is loaded. I use code like this:

NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:@"MySavedCookies"];
if([cookiesdata length]) {
    NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
    NSHTTPCookie *cookie;

    for (cookie in cookies) {
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
    }
}

and it works just fine.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexView Question on Stackoverflow
Solution 1 - Cocoa TouchgazreeseView Answer on Stackoverflow
Solution 2 - Cocoa TouchMagnusView Answer on Stackoverflow