我想从需要使用NSURLSession进行身份验证的Web服务器获取数据。我尝试了几种不同的方式,没有运气。这是我到目前为止。它正在采用协议方法didReceiveChallenge,但似乎没有进行身份验证。我收到的数据为空。NSURLSession和身份验证凭证
我检查了用户名/密码,他们是正确的。而且我通过在Safari中转到该URL并手动输入凭据并查看JSON,再次检查了URL是否正确。
@interface PlaylistData1b() <NSURLSessionDataDelegate, NSURLSessionDelegate>
@property (nonatomic,strong) NSURLSession *session;
@property (nonatomic, strong) NSString *requestString;
@end
@implementation PlaylistData1b
- (instancetype)initWithURL:(NSString *)urlString
{
self = [super init];
if(self){
_requestString = urlString;
}
return self;
}
-(void)log
{
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
_session = [NSURLSession sessionWithConfiguration:config
delegate:self
delegateQueue:nil];
[self fetchData];
}
-(void)fetchData
{
NSString *requestString = _requestString;
NSURL *url = [NSURL URLWithString:requestString];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSURLSessionDataTask *dataTask =
[self.session dataTaskWithRequest:req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"JSON: %@", jsonObject);
}];
[dataTask resume];
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
{
NSURLCredential *cred = [NSURLCredential credentialWithUser:username
password:password
persistence:NSURLCredentialPersistenceNone];
[[challenge sender] useCredential:cred forAuthenticationChallenge:challenge];
completionHandler(NSURLSessionAuthChallengeUseCredential, cred);
NSLog(@"Finished Challenge");
}
这里是我的输出。
2015-10-12 15:03:57.322 GetPlaylistData[7040:138551] Finished Challenge
2015-10-12 15:04:33.321 GetPlaylistData[7040:138788] JSON: (null)
任何帮助表示赞赏。谢谢。
只是说,感谢这个代码片断......正是我一直在寻找(和它的工作一种享受着我,调用需要Active Directory登录的内部Web服务) –