iOS5:willSendRequestForAuthenticationChallenge方法正在recursion运行

我正在使用下面的代码来validation远程服务器的用户。如果我给出正确的用户名和密码,没有问题,因为身份validation正在发生,我正在从服务器获得响应。

但是,当我给错了证书,这个方法是以recursion的方式调用,所以我不能打破这个。

请帮助我,如何打破这个,我应该能够显示身份validation失败的警报消息。

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { NSURLCredential *credential = [NSURLCredential credentialWithUser:@"username" password:@"password" persistence:NSURLCredentialPersistenceForSession]; [[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]; } } 

您需要检查错误计数并适当地取消authentication挑战:

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