Set cookies with NSURLSession

前端 未结 2 1110
广开言路
广开言路 2021-02-01 06:44

Hi I am developing one Iphone application In which I want to set cookies after server response and use that for another request. My network request looks like.

N         


        
相关标签:
2条回答
  • 2021-02-01 07:19

    You can probably get away with just using the sharedHTTPCookieStorage for NSHTTPCookieStorage, and then use setCookies:forURL:mainDocumentURL: or the single setCookie: - the latter might be better for your needs.

    If this doesn't work you might need to setup the NSURLSessionConfiguration and set the NSHTTPCookieStorage

    The docs don't state it, but the defaultSessionConfiguration might use the shared store anyway.

    NSURLSession *session = [NSURLSession sharedSession];
    [[session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
    {
        NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
    
        NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[response URL]];
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:cookies forURL:[response URL] mainDocumentURL:nil];
    
        NSLog(@"sttaus code %i", httpResp.statusCode);
        if (error) {
            [self.delegate signinWithError:error];
        }
        else {
            [self.delegate signinWithJson:data];
        }
    }] resume];
    
    0 讨论(0)
  • 2021-02-01 07:22

    I researched a lot but found one in a website of another language. The solution is to add an empty event handler for session start and end:

    protected void Session_Start(object sender, EventArgs e)
    {
    }
    protected void Session_End(object sender, EventArgs e)
    {
    }
    
    0 讨论(0)
提交回复
热议问题