我正在使用以下代码对远程服务器的用户进行身份验证。如果我提供正确的用户名和密码,则没有问题,因为身份验证正在发生,我从服务器获得响应。
但是当我提供错误的凭据时,会以递归方式调用此方法,因此我无法解决此问题。
请帮助我,如何打破这一点,以便我能够显示身份验证失败的警报消息。
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
NSURLCredential *credential = [NSURLCredential credentialWithUser:@"username"
password:@"password"
persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}
答案 0 :(得分:5)
您需要检查错误计数并相应地取消身份验证质询:
if ([challenge previousFailureCount]) {
[[challenge sender] cancelAuthenticationChallenge:challenge];
} else {
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}
答案 1 :(得分: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];
}
}