简体   繁体   中英

URLSession didReceiveChallenge is too slow

The execution of my app usually stops for 2-3 seconds (even 5 seconds) at didReceiveChallenge. Around 1 out of 10 times it takes forever. The whole thing works, but what can I do to speed it up?

Here's my code:

- (void)URLSession:(NSURLSession *)session
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
 completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * __nullable credential))completionHandler{
    NSLog(@"*** KBRequest.NSURLSessionDelegate - didReceiveChallenge IOS10");
    if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){
        if([challenge.protectionSpace.host isEqualToString:@"engine.my.server"]){
            NSURLCredential *credential = [NSURLCredential credentialForTrust: challenge.protectionSpace.serverTrust];
            completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
        }
        else{
            completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
        }
    }
}

You MUST call the completion handler EVERY time this method is called. You're only calling it for a single protection space.

When the OS calls this method on your delegate, the NSURLSession stack sits there dutifully waiting for you to call the completion handler block. If you fail to call the completion handler, your request will just sit in limbo until the request times out.

To fix this, at the bottom of the method, add:

} else {
    completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
}

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.

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