Set cookies with NSURLSession

為{幸葍}努か 提交于 2019-12-02 18:22:45
Rich

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];
Carson

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)
{
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!