Search code examples
ioscookiesnsurlconnectionsession-cookiesnsurlcredential

How to get cookie from Webserver and maintain it in iOS app?


I would like to to get fetch JSON from http://mycompany.com/page1...http://mycompany.com/page2... On the the webserver side, it requires initial login http://mycompany.com/login, and after that a cookie is maintained for the user. How do I get this behavior with NSURLConnection without having to ask for login every time? Here is the non-working code using NSURLCredential Storage. Do I need to get the cookie from webservice at loging and then send it along with later requests? I struggled with this for some time, So can you please clarify your answer.

- (IBAction)getJSON:(id)sender
{


NSURLCredential *credential = [NSURLCredential credentialWithUser:@"user"
                                                         password:@"pass"
                                                          persistence:NSURLCredentialPersistenceForSession];

NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc]
                                         initWithHost:@"myCompany.com"
                                         port:0
                                         protocol:@"http"
                                         realm:nil
                                         authenticationMethod:nil];

[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credential
                                                    forProtectionSpace:protectionSpace];


//////////GET JSON//////////////

NSError *error;
NSURL *url = [NSURL URLWithString:@"http://mycompany.com.jsonpage1"];
 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}

 //I am NOT getting JSON in this delegate
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

NSString *responseString = [[NSString alloc] initWithData:responseData    encoding:NSUTF8StringEncoding];

NSLog(@"%@",responseString);

}

Solution

  • Reading cookies:

    refer to Managing HTTP Cookies on iPhone

    Setting cookie:

    ... set dictionary with cookie properties, then:

    NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:[NSDictionary dictionaryWithObjects:object forKeys:keys]];
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
    

    but keep in mind that session cookies can expire on your server