Usted puede utilizar el marco de seguridad
#import <Security/Security.h>
Para guardar un nombre de usuario y contraseña para un servidor:
-(void) saveUsername:(NSString*)user withPassword:(NSString*)pass forServer:(NSString*)server {
// Create dictionary of search parameters
NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:(__bridge id)(kSecClassInternetPassword), kSecClass, server, kSecAttrServer, kCFBooleanTrue, kSecReturnAttributes, nil];
// Remove any old values from the keychain
OSStatus err = SecItemDelete((__bridge CFDictionaryRef) dict);
// Create dictionary of parameters to add
NSData* passwordData = [pass dataUsingEncoding:NSUTF8StringEncoding];
dict = [NSDictionary dictionaryWithObjectsAndKeys:(__bridge id)(kSecClassInternetPassword), kSecClass, server, kSecAttrServer, passwordData, kSecValueData, user, kSecAttrAccount, nil];
// Try to save to keychain
err = SecItemAdd((__bridge CFDictionaryRef) dict, NULL);
}
Para retirar:
-(void) removeAllCredentialsForServer:(NSString*)server {
// Create dictionary of search parameters
NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:(__bridge id)(kSecClassInternetPassword), kSecClass, server, kSecAttrServer, kCFBooleanTrue, kSecReturnAttributes, kCFBooleanTrue, kSecReturnData, nil];
// Remove any old values from the keychain
OSStatus err = SecItemDelete((__bridge CFDictionaryRef) dict);
}
para que diga:
-(void) getCredentialsForServer:(NSString*)server {
// Create dictionary of search parameters
NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:(__bridge id)(kSecClassInternetPassword), kSecClass, server, kSecAttrServer, kCFBooleanTrue, kSecReturnAttributes, kCFBooleanTrue, kSecReturnData, nil];
// Look up server in the keychain
NSDictionary* found = nil;
CFDictionaryRef foundCF;
OSStatus err = SecItemCopyMatching((__bridge CFDictionaryRef) dict, (CFTypeRef*)&foundCF);
// Check if found
found = (__bridge NSDictionary*)(foundCF);
if (!found)
return;
// Found
NSString* user = (NSString*) [found objectForKey:(__bridge id)(kSecAttrAccount)];
NSString* pass = [[NSString alloc] initWithData:[found objectForKey:(__bridge id)(kSecValueData)] encoding:NSUTF8StringEncoding];
}
ahora tiene que usar __bridge (fixups permiten automáticos que lo haga por usted) para convertir entre el código ObjC y C en el anterior. –
Puedes actualizar esto para ARC por favor. –
Debe comprobar si err == errSecItemNotFound después de SecItemCopyMatching –