Setting a cookie in an iPhone App

** Update 2017 **
A lot of changes to security mechanisms and cross-app communication were introduced to iOS in the recent years since this was first answered.

The below code no longer works on current iOS releases since Safari no longer accepts javascript:... in URLs and frameworks like NSURL catch these and return nil.

The one alternative that still works is to either host a website and have Safari open it or integrate such a HTML page in your app and run a small http server to host it on demand.

**iOS up to 6.x **
Since Apple has forced the sandboxing on all app store applications
there’s currently no easy way to realize your request.

You could however open a special http://-URL from your application containing javascript to place a cookie:

NSString jsURL = @"javascript:function someFunction(){ /* your javascript code here */ } someFunction();void(0)";
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: jsURL]];

Using javascript in URLs has been used by different iPhone applications to cross communicate
with MobileSafari (for example instapaper).

Another option would be to include a static HTML page in your app or on your server and instruct MobileSafari to open it.
The page in turn could set the permanent cookie.

Hope this helps!

Leave a Comment