我正在了解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;
}
}
答案 0 :(得分: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];
}
}
}
参考this链接。