简体   繁体   English

NSURLSession HTTP基本身份验证委托不起作用

[英]NSURLSession HTTP basic auth delegate does not work

I used NSURLConnection with challenge delegate, and it worked. 我将NSURLConnection与质询委托一起使用,并且有效。 I now migrate my code to session, and challenge not called. 现在,我将代码迁移到会话,并且未调用挑战。 On server side I see 401 response, but no delegate called. 在服务器端,我看到401响应,但未调用任何委托。

@interface MyDelegate : NSObject<NSURLSessionDelegate, NSURLSessionTaskDelegate>

@end

@implementation MyDelegate
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
 completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * __nullable credential))completionHandler {
// Break point here NOT called
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
 completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * __nullable credential))completionHandler {
    // Break point here NOT called

}
@end

int main(int argc, char * argv[]) {
    @autoreleasepool {
        //return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
        NSURL *url = [NSURL URLWithString:@"http://127.0.0.1:8000/upload/123"];
        NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
        req.HTTPMethod = @"PUT";
        [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        NSError *err;
        NSURLResponse *resp;
        NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:[MyDelegate new] delegateQueue:nil];
        [[session uploadTaskWithRequest:req fromData:[NSData new]]resume];
        sleep(10000);
    }
}

Do I miss something? 我想念什么吗?

Just in case: please do not advice me to create Basic HTTP auth header manually, I want to use delegate. 以防万一:请不要建议我手动创建Basic HTTP auth标头,我想使用委托。

PS: Could it be my delegate released since delegate not retained in session? PS:那是因为未派代表参加会议而释放了我的代表吗? I will try to make it static, then. 然后,我将尝试使其变为静态。

I think NSURLSession requests have to be running in a run loop. 我认为NSURLSession请求必须在运行循环中运行。 I'm not certain of this, however. 但是,我不确定。

And of course, if you were doing this in a real app, you probably would not want to block the main thread with a sleep call. 当然,如果您在真实的应用程序中执行此操作,则可能不希望通过sleep调用来阻塞主线程。 This might also be part of the problem. 这也可能是问题的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM