Reputation: 796
I was wondering how to save a cookie in Xcode. I would like to use the cookie I get from one webpage and use it to access another. I use the code below to login into the website and I would like to save a cookie I get from this connection to use it when I make another connection.
NSString *post = [NSString stringWithFormat: @"some data", _username, _password ];
// NSLog(@"%@",post);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
NSURL *url=[NSURL URLWithString:@"url"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSData *urlData;
NSHTTPURLResponse *response;
NSError *error;
urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
Update: Thanks to iOS Dev I was able to get the cookies. The code below is a for loop to nslog all the cookies name, domain, value. To help see all the cookies you currently have stored.
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
for (int i = 0; i < [cookies count]; i++) {
NSHTTPCookie *cookie = [cookies objectAtIndex:i];
NSLog(@"Cookie Name: %@", [cookie name]);
NSLog(@"Cookie Domain: %@", [cookie domain]);
NSLog(@"Cookie Value: %@", [cookie value]);
}
Upvotes: 1
Views: 1850
Reputation: 10424
When you get a response back the updated cookies will be available in NSHttpCookieStorage
single ton.
You can access it by
NSArray *cookies = [[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]
Upvotes: 1