cleaning out credentialsForProtectionSpace to have only one key value set. NSURLCredentialStorage

2.2k views Asked by At

I am learning about the NSURLCredentialStorage and have a situation. As I am developing my app I happened to store two usernames with passwords using the following code. The problem I have is, there is no need to store the two sets of uname/pword combos. So my question is, how do I reset the storage and start fresh?

Here is how I load the credentials: Mind you I am using the load from ObjectiveResource example and it grabs object at index 0. I want there to only be 1 object pair.

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

}

1

There are 1 answers

2
Paresh Navadiya On BEST ANSWER

reset credential using 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];
        }
    }
}

Refer this link.