1

First time I start my app and log in, I get a session, which I need to do some of my queries (it's how I know who's logged in).

Anyway, if I kill the app and relaunch it, I get a NEW session id. Why? In the past my ios apps stored the session cookies.. I thought.

JP.
  • 544
  • 5
  • 20

2 Answers2

4

You need to manually persist cookies to disk with NSCoding before the app terminates, and then load them on app launch, like so:

NSData *cookiesData = [[NSUserDefaults standardUserDefaults] objectForKey:@"SavedCookies"];
if ([cookiesData length] > 0) {
    for (NSHTTPCookie *cookie in [NSKeyedUnarchiver unarchiveObjectWithData:cookiesData]) {
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
    }
}
raidfive
  • 6,603
  • 1
  • 35
  • 32
mattt
  • 19,544
  • 7
  • 73
  • 84
2

HTTP sessions are designed to be short-lived. Typically this is set to be the life of the browser or more recently the life of the browser-tab. Some browsers will now store sessions between app launches, so long as the browser-tab is left open, but this is a convenience for users.

If your previous apps maintained session between App starts and termination that was a bug in implementation on how the sessions were stored.

I wouldn't recommend using sessions to store long-lived data. For that, use NSUserDefaults or consider using SqlLite storage.

Edit to Address Comment Question:

How should I build the app so the user only has to login once when the app is installed.

There are a number of ways to accomplish this, depending what parts of the system you own.

The easiest scenario conceptually is that you own the web-service. In which case you can store the users credentials, and each time the app is started, log the user in, and use that session id as you have now.

When building the UI for this, I would have a checkbox that asks the user to remember me; basically asking them for permission to store their creds on the phone.

The trick part is how to properly secure the user credentials.

Alan
  • 45,915
  • 17
  • 113
  • 134
  • How should I accomplish this scenario then? User logs in, user kills app, user launches app, user is still logged in (e.g. the server still has a way to recognize user and access data accordingly) – JP. Nov 04 '12 at 19:28