iOS5:willSendRequestForAuthenticationChallenge方法正在运行递归



我正在使用以下代码对远程服务器的用户进行身份验证。如果我提供正确的用户名和密码,则没有问题,因为身份验证正在进行并且我从服务器获得响应。

但是当我提供错误的凭据时,此方法以递归方式调用,因此我无法打破它。

请帮助我,如何打破这种情况,以便我应该能够显示身份验证失败警报消息。

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    NSURLCredential *credential = [NSURLCredential credentialWithUser:@"username"
                                                             password:@"password"
                                                          persistence:NSURLCredentialPersistenceForSession];
    [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];    
}

您需要检查错误计数并相应地取消身份验证质询:

if ([challenge previousFailureCount]) {
    [[challenge sender] cancelAuthenticationChallenge:challenge];
} else {
    [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}

试试这个。

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
        {
        if ([challenge previousFailureCount] > 0) {
                // do something may be alert message
            } 
        else
        {
            NSURLCredential *credential = [NSURLCredential credentialWithUser:@"username"
                                                                     password:@"password"
                                                                  persistence:NSURLCredentialPersistenceForSession];
            [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; 
        }
}

最新更新