首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >清除credentialsForProtectionSpace以仅设置一个键值。NSURLCredentialStorage

清除credentialsForProtectionSpace以仅设置一个键值。NSURLCredentialStorage
EN

Stack Overflow用户
提问于 2012-12-04 09:08:28
回答 1查看 2.2K关注 0票数 2

我正在学习关于NSURLCredentialStorage的知识,并且有一个情况。当我开发我的应用程序时,我碰巧使用以下代码存储了两个用户名和密码。我的问题是,没有必要存储两组uname/pword组合。因此,我的问题是,如何重置存储并重新开始?

下面是我加载凭据的方式:请注意,我使用的是load from ObjectiveResource示例,它在索引0处抓取对象。我希望只有一个对象对。

代码语言:javascript
复制
- (void)loadCredentialsFromKeychain {
NSDictionary *credentialInfo = [[NSURLCredentialStorage sharedCredentialStorage] credentialsForProtectionSpace:[self protectionSpace]];

// Assumes there's only one set of credentials, and since we
// don't have the username key in hand, we pull the first key.
NSArray *keys = [credentialInfo allKeys];
if ([keys count] > 0) {
    NSString *userNameKey = [[credentialInfo allKeys] objectAtIndex:0]; 
    NSURLCredential *credential = [credentialInfo valueForKey:userNameKey];
    self.login = credential.user;
    self.password = credential.password;
}

}

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-12-04 12:21:29

使用NSURLCredentialStorage removeCredential:forProtectionSpacereset credential

代码语言:javascript
复制
// reset the credentials cache...
NSDictionary *credentialsDict = [[NSURLCredentialStorage sharedCredentialStorage] allCredentials];

if ([credentialsDict count] > 0) {
    // the credentialsDict has NSURLProtectionSpace objs as keys and dicts of userName => NSURLCredential
    NSEnumerator *protectionSpaceEnumerator = [credentialsDict keyEnumerator];
    id urlProtectionSpace;

    // iterate over all NSURLProtectionSpaces
    while (urlProtectionSpace = [protectionSpaceEnumerator nextObject]) {
        NSEnumerator *userNameEnumerator = [[credentialsDict objectForKey:urlProtectionSpace] keyEnumerator];
        id userName;

        // iterate over all usernames for this protectionspace, which are the keys for the actual NSURLCredentials
        while (userName = [userNameEnumerator nextObject]) {
            NSURLCredential *cred = [[credentialsDict objectForKey:urlProtectionSpace] objectForKey:userName];
            NSLog(@"cred to be removed: %@", cred);
            [[NSURLCredentialStorage sharedCredentialStorage] removeCredential:cred forProtectionSpace:urlProtectionSpace];
        }
    }
}

请参阅this链接。

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

https://stackoverflow.com/questions/13694559

复制
相关文章

相似问题

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