Channing
Channing

Reputation: 31

How to set/check cookies in iPhone app?

I am trying to set a cookie and also check if it is there, does anybody have any sample code for this? All I found was the TTPCookieStorage class reference, but it would be helpful if I could see an implementation example.

Upvotes: 3

Views: 8490

Answers (3)

Matt Gallagher
Matt Gallagher

Reputation: 14968

Only the server of an HTTP connection should be setting cookies. It does this with a Set-Cookie field in the headers.

The cookie storage you linked handles all NSURLConnection cookie action (both getting and setting) and generally -- you shouldn't change the cookies yourself. If you want to override, you can't use NSURLConnection and will need to use a CFReadStreamRef and handle the communication and build a CFHTTPMessageRef manually.

You will need to handle cookies if you're implementing the server side of HTTP communication.

If you're implementing a server using CFHTTPMessageRef, then:

NSDate *expiryDate = /* set some date value */

CFHTTPMessageSetHeaderFieldValue(
    response,
    (CFStringRef)@"Set-Cookie",
    (CFStringRef)[NSString stringWithFormat:
            @"SomeCookieName=%@;Path=/;expires=%@",
            someStringValue,
            [dateFormat stringFromDate:expiryDate]]);

where response is the CFHTTPMessageRef you're using for the reply. You can use CFHTTPMessageCopyAllHeaderFields and get the object for key "Cookie" to extract cookies from the client in a CFHTTPMessageRef header.

Upvotes: 4

drawnonward
drawnonward

Reputation: 53659

Cookies are for web pages. If you want to display web pages, use a UIWebView. If you want to store persistent data, use NSUserDefaults. If you want to parse cookies sent from a server, use NSURLConnection and parse the headers. If you want to see what cookies have been set by a UIWebView running in your applicaiton, use NSHTTPCookieStorage.

NSHTTPCookieStorage Class Reference

These cookies are shared among all applications and are kept in sync cross-process.

That is only true if your application runs as root on the iPhone.

Upvotes: 1

Related Questions