tags:

views:

806

answers:

3

Hi, 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 this, but it would be helpful if I could see an implementation example. http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSHTTPCookieStorage_Class/Reference/Reference.html

+1  A: 

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.

drawnonward
+1  A: 

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.

Matt Gallagher