34

I want to port a python app that uses mechanize for the iPhone. This app needs to login to a webpage and using the site cookie to go to other pages on that site to get some data.

With my python app I was using mechanize for automatic cookie management. Is there something similar for Objective C that is portable to the iPhone?

Thanks for any help.

benzado
  • 82,288
  • 22
  • 110
  • 138
dan
  • 5,377
  • 13
  • 39
  • 44

3 Answers3

72

NSURLConnection gives you cookie management for free. From the URL Loading System Programming Guide:

The URL loading system automatically sends any stored cookies appropriate for an NSURLRequest. unless the request specifies not to send cookies. Likewise, cookies returned in an NSURLResponse are accepted in accordance with the current cookie acceptance policy.

Sunil Pandey
  • 7,042
  • 7
  • 35
  • 48
Steve Madsen
  • 13,465
  • 4
  • 49
  • 67
44

You can use the NSURLConnection class to perform a HTTP request to login the website, and retrieve the cookie. To perform a request, just create an instance of NSURLConnection and assign a delegate object to it.

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com/"]];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];

Then, implement a delegate method.

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    NSDictionary *fields = [httpResponse allHeaderFields];
    NSString *cookie = [fields valueForKey:@"Set-Cookie"]; // It is your cookie
}

Retain or copy the cookie string. When you want to perform another request, add it to your HTTP header of your NSURLRequest instance.

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com/"]];
[request addValue:cookie forHTTPHeaderField:@"Cookie"];
Sabby
  • 2,586
  • 2
  • 27
  • 41
zonble
  • 4,213
  • 1
  • 21
  • 14
  • 26
    You don't need to do this, NSURLConnection automatically stores and sends cookies unless you explicitly tell it not to. – benzado Apr 20 '10 at 15:33
  • 1
    Even though this shouldn't be necessary fixed a suspected bug in iOS 4.2GM – crackity_jones Nov 12 '10 at 00:09
  • How would one detect that a Session has expired client-side? What callback should we expect? Or is it just a matter of checking to see if the request (with that session id) succeeded or not? – Cole Mar 14 '13 at 16:17
0

@zonble's answer only works in my localhost; If the server is not running locally, the "Set-Cookie" header is missing from the NSDictionary *fields = [HTTPResponse allHeaderFields];

Finally I found @benzado's solution works fine. Also see: iphone nsurlconnection read cookies @Tal Bereznitskey's answer.

Community
  • 1
  • 1
Ranger Way
  • 539
  • 6
  • 11