2012-12-04 42 views
2

我正在學習NSURLCredentialStorage並且有一種情況。在開發我的應用程序時,我偶然使用以下代碼存儲了兩個使用密碼的用戶名。我的問題是,沒有必要存儲兩組uname/pword組合。所以我的問題是,如何重置存儲並重新開始?清除credentialsForProtectionSpace以僅設置一個鍵值。 NSURLCredentialStorage

以下是我如何加載憑據:請注意,我使用的是來自ObjectiveResource示例的負載,它抓取索引爲0的對象。我希望只有一對對象。

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

reset credential使用NSURLCredentialStorageremoveCredential: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鏈接。

+0

謝謝。我懷疑有人有一些片段,並願意分享。我剛剛在閱讀文檔時發現了removeCredential,並且即將試用。我能夠通過設置和獲取默認憑據來克服我的直接障礙,但最終希望清理保護空間。 – Nungster

+0

這就是一些很好的剪輯在這裏。謝謝先生,正是我需要的! – masi

相關問題