什么时候URLSession:didReceiveChallenge:completionHandler:
方法NSURLSessionDelegate
被调用?当我收到403状态代码的响应时是否调用了它?
如果我应该在授权后更改第二个请求的请求主体,可以使用此委托方法进行授权吗?(我应该改变@"ticket"
)
NSURLSession *session = [NSURLSession sharedSession];
NSError *error;
NSDictionary *mapData = @{
@"userIdentity": @{
@"ticket": [SecretStorage sharedInstance].ticket,
@"hotelId": [SecretStorage sharedInstance].hotelId,
@"language": @"ru"
}
};
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"example.com"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.f];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"%@", json);
}];
[dataTask resume];
NSURLSession的委托中有两种不同的质询/响应处理程序。您要实现的第一个会话是会话级别的,并且基本上处理服务器级别的身份验证。
-对于会话级别的挑战-NSURLAuthenticationMethodNTLM,NSURLAuthenticationMethodNegotiate,NSURLAuthenticationMethodClientCertificate或NSURLAuthenticationMethodServerTrust-NSURLSession对象调用会话委托的URLSession:didReceiveChallenge:completionHandler:方法。如果您的应用程序不提供会话委托方法,则NSURLSession对象将调用任务委托的URLSession:task:didReceiveChallenge:completionHandler:方法来处理挑战。
-对于非会话级别的挑战(所有其他挑战),NSURLSession对象调用会话委托的URLSession:task:didReceiveChallenge:completionHandler:方法来处理挑战。如果您的应用提供了会话委托,并且您需要处理身份验证,那么您必须在任务级别处理身份验证,或者提供一个任务级别的处理程序来显式调用每个会话处理程序。对于非会话级别的挑战,不会调用会话委托的URLSession:didReceiveChallenge:completionHandler:方法。
因此,您可能想通过在委托对象中添加对NSURLSessionTaskDelegate的协议支持并在任务级别提供处理程序来处理任务级别的身份验证URLSession(_:task:didReceiveChallenge:completionHandler:)
。
欲了解更多信息,请访问此链接
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句