首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AuthenticationChallenge只调用一次

AuthenticationChallenge只调用一次
EN

Stack Overflow用户
提问于 2015-12-11 01:40:42
回答 1查看 99关注 0票数 0

我正在使用NSURLConnection连接到服务器。它使用基本授权。这是我的代码:

代码语言:javascript
复制
- (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...不被调用。这意味着函数返回服务器是可访问的,但实际上不是。

有什么想法可以改进我的代码吗?非常感谢。

EN

回答 1

Stack Overflow用户

发布于 2015-12-11 04:49:23

如果你看看苹果AdvancedURLConnections中的CredentialsController.m,就会发现它们说明了如何清除凭据。

代码语言:javascript
复制
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代码示例还说明了如何从密钥链中清除凭据。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34208370

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档