AFNetworking AFHTTPSessionManager POST 调用了两次

AFNetworking AFHTTPSessionManager POST called twice

我正在使用新的 afnetworking 3.0 库发出网络请求以使用 AFHTTPSessionmanager 进行登录。因此,当我执行 POST 调用时,如果收到 401 的响应,则会静默调用另一个网络请求。

如何通过在失败回调时不再调用服务来避免它?

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

如果您收到身份验证质询,您会看到第二个请求。

如果需要,您可以简单地拒绝授权质询,这会停止第二个请求:

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

或者,如果您想继续进行身份验证,您可以执行以下操作:

[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;
}];

这完全取决于您如何在网络服务上对用户进行身份验证。