2016-04-21 64 views
0

URLSession:didReceiveChallenge:completionHandler:方法NSURLSessionDelegate被调用?当我收到403状态代码的回复时,它是否打电话给我?使用NSURLSession委托授权

如果我在授权后更改第二个请求的请求正文,我可以使用此委托方法进行授权吗? (我应该改变@"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]; 

回答

2

有在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:)

欲了解更多信息,请访问link