Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persisting Cookies In An iOS Application?

People also ask

What is a persistence cookie?

Persistent cookies are stored on a user's device to hold usage information, settings, personalizations, or sign-on credentials. The primary purpose of persistent cookies is to provide users with an immersive and seamless browsing experience by auto-filling information that the user may have already provided.

Do iOS apps have cookies?

A normal iOS application does not contains cookies. An app will have cookies only if the application has one or more web views. To check where are the app cookies stored on iPhone, On an iPhone, go to Settings -> Safari -> Advanced -> Website Data and you will see all cookies stored on your device.

Where are persistent cookies stored?

Persistent cookies which are set while you are visiting a website are stored on your hard drive for a length of time set by the website.

Can cookies be permanent?

A persistent cookie is a data file capable of providing websites with user preferences, settings and information for future visits. Persistent cookies provide convenient and rapid access to familiar objects, which enhances the user experience (UX). A persistent cookie is also known as a stored or permanent cookie.


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.


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.