lifemoveson lifemoveson - 1 month ago 44
iOS Question

AFNetworking AFHTTPSessionManager POST called twice

I am using the new afnetworking 3.0 library to make network request to login using AFHTTPSessionmanager. So when I do a POST Call and in the response if I get 401, there is another network request being called silently.

How can I avoid it by not calling the service again on the failure callback ?

[manager POST:[[urlReq URL] absoluteString] parameters:nil progress:nil success:^(NSURLSessionTask *operation, id responseObject)

Rob Rob
Answer

You'll see that second request if you're receiving an authentication challenge.

You can, if you want, simply reject the authorization challenge, which stops the second request:

[manager setTaskDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession * _Nonnull session, NSURLSessionTask * _Nonnull task, NSURLAuthenticationChallenge * _Nonnull challenge, NSURLCredential *__autoreleasing  _Nullable * _Nullable credential) {
    return NSURLSessionAuthChallengeCancelAuthenticationChallenge;
}];

Or, if you want to go ahead and authenticate, you could do something like:

[manager setTaskDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession * _Nonnull session, NSURLSessionTask * _Nonnull task, NSURLAuthenticationChallenge * _Nonnull challenge, NSURLCredential *__autoreleasing  _Nullable * _Nullable credential) {
    if (challenge.previousFailureCount == 0) {
        *credential = [NSURLCredential credentialWithUser:self.user password:self.password persistence:NSURLCredentialPersistenceForSession];
        return NSURLSessionAuthChallengeUseCredential;
    }

    return NSURLSessionAuthChallengeCancelAuthenticationChallenge;
}];

It all depends upon how you're authenticating users on your web service.