0

I would like to to get fetch JSON from http://mycompany.com/jsonpage1..etc. The webserver requires initial login http://mycompany.com/login, and after that a cookie is maintained for the user. How do I get this behavior with NSURLCredentialStorage without asking to login every time? Here is the non-working code using NSURLCredential Storage

- (IBAction)getJSON:(id)sender
{

//  [self establishSession];

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);

}
software2007
  • 51
  • 1
  • 7

1 Answers1

0

You can try AFNetworking library and subclass AFHTTPClient in which you can encapsulate your authentication for each request.

manikal
  • 953
  • 7
  • 30
  • If you want to use NSURLConnection you can checkout [NSURLCredentialStorage](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLCredentialStorage_Class/Reference/Reference.html), [this](http://stackoverflow.com/a/501869/82813) answer might help you – manikal Aug 19 '12 at 15:29
  • I can look into AFHTTPClient. Will the webserver respond correctly to requests with embedded credentials? As far as I know the webserver maintains a cookie at initial login and allows fetching pages while session is alive. if AFHTTPClient works fine with this concept, I will give it a go. – software2007 Aug 19 '12 at 15:31
  • Can't seem to get it to work- See Edited original Post. What am I missing? Any other methods I have to take care of? – software2007 Aug 20 '12 at 10:34