iOS: How can i receive HTTP 401 instead of -1012 NSURLErrorUserCancelledAuthentication

后端 未结 5 1116
一整个雨季
一整个雨季 2020-12-01 01:57

I have a problem similar to the one described in the link below.

NSHTTPURLResponse statusCode is returning zero when it should be 401

I use [NSURLConne

5条回答
  •  旧时难觅i
    2020-12-01 02:38

    I was facing the issue not receiving 401 Unauthorized error code (was getting nil response also didReceiveResponse method was not getting called) instead receiving -999 cancelled error. The mistake I was doing in my code is: In didReceiveChallenge: delegate method,

    if (challenge.previousFailureCount == 0)
    {
        //handle certificate trust
        completionHandler (NSURLSessionAuthChallengeUseCredential, newCredential);
    }
    else
    {
        completionHandler (NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
    }
    

    The NSURLSessionAuthChallengeCancelAuthenticationChallenge was resulting in the -999 error and there was no 401 response obtained. Instead when I used completionHandler (NSURLSessionAuthChallengePerformDefaultHandling, nil); I was receiving 401 response in didReceiveResponse: delegate method as expected.

    Note from iOS documentation https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/URLLoadingSystem/NSURLSessionConcepts/NSURLSessionConcepts.html, If we cancel the urlsession then it will be reported as cancelled, but not as 401 error in response.

    Note: NSURLSession does not report server errors through the error parameter. The only errors your delegate receives through the error parameter are client-side errors, such as being unable to resolve the hostname or connect to the host. The error codes are described in URL Loading System Error Codes.
    Server-side errors are reported through the HTTP status code in the NSHTTPURLResponse object. For more information, read the documentation for the NSHTTPURLResponse and NSURLResponse classes.
    

提交回复
热议问题