Multiple NSURLRequests with different cookies (asynchronous)

by Hans Pinckaers

I searched the whole internet for a solution but I didn’t find one answer to this problem. I managed to get it to work. My problem was that I had several NSURLRequests who had to connect to one webservice, without an API, so I had to login behind the scenes with the provided login form from the normal website. This webpage uses cookies, but the NSURLRequest object on the iPhone uses a shared cookie storage. I wanted to use different accounts on one webservices with each their own cookies.

The solution was quite simple. You have to save the cookies after you get the response headers and you have to set them before doing the request. You also have to turn off the cookie handling via the shared cookie provider.

Here is the code for saving the cookies. self.currentCookies is an NSArray, you have to be sure that the delegate of the NSURLConnection is the same class.

-(void) connection:(NSURLConnection *)connection 
	didReceiveResponse:(NSURLResponse *)response
{
    self.currentCookies = [NSHTTPCookie 
	cookiesWithResponseHeaderFields:[response allHeaderFields] 
	forURL:[NSURL URLWithString:@""]];
}

Here is the code for using the saved cookies for a new request:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] 
				initWithURL:url]; 

[request setHTTPMethod: @"POST"];
[request setHTTPShouldHandleCookies:NO];

if(self.currentCookies != nil){
    [request setAllHTTPHeaderFields:
	[NSHTTPCookie requestHeaderFieldsWithCookies:
		self.currentCookies]];
}
NSURLConnection *connection = [[NSURLConnection alloc] 
				initWithRequest:request delegate:self];