Is it possible to set a cookie manually using sharedHTTPCookieStorage for a UIWebView?

Yes, you can do this. First, in applicationDidBecomeActive add this line

[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];

The cookieAcceptPolicy is shared across apps and can be changed without your knowledge, so you want to be sure you have the accept policy you need every time your app is running.

Then, to set the cookie:

NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[cookieProperties setObject:@"testCookie" forKey:NSHTTPCookieName];
[cookieProperties setObject:@"someValue123456" forKey:NSHTTPCookieValue];
[cookieProperties setObject:@"www.example.com" forKey:NSHTTPCookieDomain];
[cookieProperties setObject:@"www.example.com" forKey:NSHTTPCookieOriginURL];
[cookieProperties setObject:@"https://stackoverflow.com/" forKey:NSHTTPCookiePath];
[cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion];

// set expiration to one month from now or any NSDate of your choosing
// this makes the cookie sessionless and it will persist across web sessions and app launches
/// if you want the cookie to be destroyed when your app exits, don't set this
[cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires];

NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];

This cookie has the name testCookie and value someValue123456 and will be sent with any http request to www.example.com.

For one big caveat to setting cookies, please see my question here!

NSHTTPCookieStorage state not saved on app exit. Any definitive knowledge/documentation out there?

Leave a Comment