Get cookies from NSHTTPURLResponse

I have a very strange problem, I am requesting a URL and I want to receive cookies from it, I used this method to receive cookies:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response; NSDictionary *fields = [HTTPResponse allHeaderFields]; NSString *cookie = [fields valueForKey:"Set-Cookie"]; } 

BUT cookies are not filled out, there is no field, I checked it on PostMan, there are all cookies.

I also used this method when running NSURLRequest .

 [request setHTTPShouldHandleCookies:YES]; 

Where is the problem?

NOTE. This problem applies to iOS, I have an Android version and it works fine, and all cookies are there.

+5
objective-c cookies nsurlrequest
source share
4 answers

@ biloshkurskyi.ss the answer is spot on top.

I spent half a day trying to figure out why some of my cookies did not appear in my .allHeaderFields answer on iOS, but it was on Android (using the same service).

The reason is that some cookies are retrieved in advance and stored in a shared cookie storage. They will not be displayed in all header fields.

Here is the quick version 3 of the answer, if anyone needs it:

 let request = URLRequest(url: myWebServiceUrl) let session = URLSession.shared let task = session.dataTask(with: request, completionHandler: { (data, response, error) in if let error = error { print("ERROR: \(error)") } else { print("RESPONSE: \(response)") if let data = data, let dataString = String(data: data, encoding: .utf8) { print("DATA: " + dataString) } for cookie in HTTPCookieStorage.shared.cookies! { print("EXTRACTED COOKIE: \(cookie)") //find your cookie here instead of httpUrlResponse.allHeaderFields } } }) task.resume() 
+6
source

Have you tried the following code example, it should work:

 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSArray *cookies =[[NSArray alloc]init]; cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[NSURL URLWithString:@""]]; // send to URL, return NSArray } 
+11
source

Try this code:

 for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) { NSLog(@"name: '%@'\n", [cookie name]); NSLog(@"value: '%@'\n", [cookie value]); NSLog(@"domain: '%@'\n", [cookie domain]); NSLog(@"path: '%@'\n", [cookie path]); } 
+7
source
 for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) { NSLog(@"name: '%@'\n", [cookie name]); NSLog(@"value: '%@'\n", [cookie value]); NSLog(@"domain: '%@'\n", [cookie domain]); NSLog(@"path: '%@'\n", [cookie path]); } 

Second code:

 NSHTTPURLResponse *HTTPResponsesss = (NSHTTPURLResponse *)response; NSDictionary *fields = [HTTPResponsesss allHeaderFields]; NSString *cookie = [fields valueForKey:@"Set-Cookie"]; // It is your cookie 

NSLog (@ "% @", cookie);

Both codes work fine.

0
source

All Articles