Persisting Cookies In An iOS Application?
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.