I used NSURLConnection
with challenge delegate, and it worked. I now migrate my code to session, and challenge not called. On server side I see 401 response, but no delegate called.
@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.
PS: Could it be my delegate released since delegate not retained in session? I will try to make it static, then.
I think NSURLSession requests have to be running in a run loop. 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. This might also be part of the problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.