Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
797 views
in Technique[技术] by (71.8m points)

objective c - Get cookies from NSHTTPURLResponse

I've an extremely weird problem, I'm requesting a URL and I want to get the cookies from it, I've used this way to get the cookies:

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

BUT the cookies is not complete, there is some field is missing, I've checked it on PostMan, all the cookies is there.

I've used also this method when initiating the NSURLRequest.

[request setHTTPShouldHandleCookies:YES];

Where is the problem?

NOTE: This problem is on iOS, I've an android version and it's working fine and all the cookies is there.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Did you tried following code sample, 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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...