NSURLCredentialStorage

NSURLCredentialStorage

我正在学习有关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;
}

}

最佳答案

使用reset credentialNSURLCredentialStorage 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];
        }
    }
}

请参阅this链接。

09-11 17:25