Multiple NSURLRequests with different cookies (asynchronous)
by Hans Pinckaers
I searched the whole internet for a solution but I didn’t find one. Yet I managed to get it to work. My problem was that I had several NSURLRequests who had to connect to one internet 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];
Hello
Nice, post here will came back
continue updating your blog
[...] also tried this hint here on specifically storing the cookies and passing them again. http://www.hanspinckaers.com/multiple-nsurlrequests-with-different-cookies. There’s another blog on the web suggesting to add a “#” to each URL in order to [...]