我正在使用NSURLConnection连接到服务器。它使用基本授权。这是我的代码:
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if ([challenge previousFailureCount] == 0) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSURLCredential *newCredential = [NSURLCredential credentialWithUser:[defaults objectForKey:@"SavedUserName"]
password:[defaults objectForKey:@"SavedPassword"]
persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
}
else {
[self doAlert:@"Cannot acces server" omg:@"Check your login properties"];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"11111111111");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(@"222222222");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"333333333333");
}
- (void)checkIfCanLogin{
[conn cancel];
conn = nil;
//setting request and so on
conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[conn start];
}
首次尝试就是一切都好。 - 我输入错误的pw,调用Alert。当我输入正确的密码连接加载。但是当我建立连接时,我更改密码,然后再调用checkIfCanLogin, - (void)didRecieveAuth ...不被调用。这意味着函数返回服务器是可访问的,但实际上并非如此。
如何改进我的代码?非常感谢。
答案 0 :(得分:0)
如果您查看Apple CredentialsController.m
中的AdvancedURLConnections,则会说明如何清除凭据。
NSURLCredentialStorage *store = [NSURLCredentialStorage sharedCredentialStorage];
assert(store != nil);
for (NSURLProtectionSpace * protectionSpace in [store allCredentials]) {
NSDictionary *userToCredentialMap = [[NSURLCredentialStorage sharedCredentialStorage] credentialsForProtectionSpace:protectionSpace];
assert(userToCredentialMap != nil);
for (NSString * user in userToCredentialMap) {
NSURLCredential *credential = [userToCredentialMap objectForKey:user];
assert(credential != nil);
[store removeCredential:credential forProtectionSpace:protectionSpace];
}
}
Credentials.m
代码示例还说明了如何从密钥链中清除凭据。