2

我正在学习 NSURLCredentialStorage 并且有一个情况。在开发我的应用程序时,我碰巧使用以下代码存储了两个带有密码的用户名。我遇到的问题是,不需要存储两组 uname/pword 组合。所以我的问题是,如何重置存储并重新开始?

这是我加载凭据的方式:请注意,我正在使用来自 ObjectiveResource 示例的加载,它在索引 0 处抓取对象。我希望只有 1 个对象对。

- (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;
}

}

4

1 回答 1

4

reset credential使用NSURLCredentialStorage removeCredential:forProtectionSpace

// 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];
        }
    }
}

参考这个链接。

于 2012-12-04T04:21:29.360 回答