在我的问题中原谅点符号。
我正在使用NSURLSession尝试登录网站。 Apple的文档建议以这种方式处理身份验证挑战。
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler
{
NSURLCredential *credential = [NSURLCredential credentialWithUser:@"<email>"
password:@"<password>"
persistence:NSURLCredentialPersistenceNone];
[[challenge sender] useCredential:credential
forAuthenticationChallenge:challenge];
}
问题是[挑战发件人]返回nil。我在设置中遗漏了什么吗?
答案 0 :(得分:2)
不确定您是否想过这个,但是您应该使用完成处理程序来代替旧的useCredential方法:
completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
答案 1 :(得分:0)
您可以尝试使用http标头授权进行会话授权:
NSString *userPasswordString = [NSString stringWithFormat:@"%@:%@", user, password];
NSData * userPasswordData = [userPasswordString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64EncodedCredential = [userPasswordData base64EncodedStringWithOptions:0];
NSString *authString = [NSString stringWithFormat:@"Basic %@", base64EncodedCredential];
configuration.HTTPAdditionalHeaders = @{@"Authorization": authString};