4

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

但是当我给出错误的凭据时,这个方法会以递归方式调用,所以我无法打破这个。

请帮助我,如何解决这个问题,以便我应该能够显示身份验证失败警报​​消息。

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{

    NSURLCredential *credential = [NSURLCredential credentialWithUser:@"username"
                                                             password:@"password"
                                                          persistence:NSURLCredentialPersistenceForSession];
    [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];    
}
4

2 回答 2

5

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

if ([challenge previousFailureCount]) {
    [[challenge sender] cancelAuthenticationChallenge:challenge];
} else {
    [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}
于 2012-05-23T14:47:19.360 回答
4

试试这个。

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

}
于 2012-05-23T14:54:34.480 回答