您可以通过执行以下步骤来做到这一点。
1)#import<Security/Security.h>
在你的项目中。
2) 使用SecItemAdd方法将您的详细信息保存到钥匙串。
-(void) saveUsername:(NSString*)user withPassword:(NSString*)pass forServer:(NSString*)server {
// Create dictionary of search parameters
NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:kSecClassInternetPassword, kSecClass, server, kSecAttrServer, kCFBooleanTrue, kSecReturnAttributes, nil];
// Remove any old values from the keychain
OSStatus err = SecItemDelete((CFDictionaryRef) dict);
// Create dictionary of parameters to add
NSData* passwordData = [pass dataUsingEncoding:NSUTF8StringEncoding];
dict = [NSDictionary kSecClassInternetPassword, kSecClass, server, kSecAttrServer, passwordData, kSecValueData, user, kSecAttrAccount, nil];
// Try to save to keychain
err = SecItemAdd((CFDictionaryRef) dict, NULL);
}
3)即使您删除了应用程序,也可以从钥匙串中获取存储的数据。
-(void) getCredentialsForServer:(NSString*)server {
// Create dictionary of search parameters
NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:kSecClassInternetPassword, kSecClass, server, kSecAttrServer, kCFBooleanTrue, kSecReturnAttributes, nil];
// Look up server in the keychain
NSDictionary* found = nil;
OSStatus err = SecItemCopyMatching((CFDictionaryRef) dict, (CFDictionaryRef*) &found);
if (!found) return;
// Found
NSString* user = (NSString*) [found objectForKey:kSecAttrAccount];
NSString* pass = [[NSString alloc] initWithData:[found objectForKey:kSecValueData] encoding:NSUTF8StringEncoding];
UIAlertView * alertView=[[UIAlertView alloc] initWithTitle:@"Key found" message:[NSString stringWithFormat:@"user : %@ pass :%@",user,pass] delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil] ;
[alertView show];
NSLog(@"user %@ : pass %@", user,pass);
}
4)如果你想从钥匙串中删除这个属性字典,你可以这样做。
-(void) removeAllCredentialsForServer:(NSString*)server {
// Create dictionary of search parameters
NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:kSecClassInternetPassword, kSecClass, server, kSecAttrServer, kCFBooleanTrue, kSecReturnAttributes, kCFBooleanTrue, kSecReturnData, nil];
// Remove any old values from the keychain
OSStatus err = SecItemDelete((CFDictionaryRef) dict);
}