Does NSURLConnection automatically persist cookies sent from server?

RubyGladiator picture RubyGladiator · Aug 19, 2012 · Viewed 17.7k times · Source

I logged into my tornado backend from ios and sent back a secure_cookie and i noticed that i could also request other information as long as i validated the secure_cookie that i set. How long does NSURLConnection persist the cookie or will the cookie be deleted once they close the app?

This is mentioned in the Apple docs:

The URL loading system automatically sends any stored cookies appropriate for an NSURLRequest. unless the request specifies not to send cookies.

Answer

Adam B picture Adam B · Aug 21, 2012

A few facets to your question.

To start with, NSURLConnection will, by default, manage cookies based on the settings for the device. It will save the cookies to the store and send them as appropriate (when the domain matches an existing cookie). This means if you make a request from a URL with a cookie saved in the cookie store, it will be sent. This explains the behavior you mentioned. Generally, with the default settings, the cookie will persist for quite a while.

This initial statement, however, maybe is not helpful for your needs. I am assuming you may want to have control over the expiration of (or keep around "forever") this secure_cookie field so your app does not have to authenticate further in the future.

In this case, NSHTTPCookieStorage is the place to look. This class will allow you to both retrieve:

[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:@"http://example.com"]]

and set:

[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie] (plus setting up the cookie dictionary object)

Based on experience and the feedback of others online, you should note that the cookie storage is not always 100% reliable. If you would like to be sending a specific cookie and value to the server, you should store that value with your app (prefs or Core Data, for example), and reset the cookie with the appropriate NSHTTPCookieStorage at each startup.