2

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

}

Mike Abdullah
  • 14,933
  • 2
  • 50
  • 75
Nungster
  • 726
  • 8
  • 28

1 Answers1

4

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.

Quentin
  • 3,971
  • 2
  • 26
  • 29
Paresh Navadiya
  • 38,095
  • 11
  • 81
  • 132
  • Thanks. I suspected someone had some snippets and were willing to share. I just found the removeCredential yesterday while reading the documentation, and was about to try it out. I was able to get past my immediate roadblock by setting and getting a default credential, but eventually wanted to clean up the protectionSpace. – Nungster Dec 05 '12 at 15:14
  • Thats some fine snipped here. Thank you sir, just what i needed! – omni Apr 21 '14 at 17:18