我正在使用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...不被调用。这意味着函数返回服务器是可访问的,但实际上不是。
有什么想法可以改进我的代码吗?非常感谢。
发布于 2015-12-11 04:49:23
如果你看看苹果AdvancedURLConnections中的CredentialsController.m,就会发现它们说明了如何清除凭据。
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代码示例还说明了如何从密钥链中清除凭据。
https://stackoverflow.com/questions/34208370
复制相似问题