Normally, we use Nsuserdefaults to store data information, but for some private information, such as passwords, certificates, and so on, we need to use a more secure keychain. The information stored in the keychain is not lost because the app is deleted, and is still valid after the user has reinstalled the app, and the data is still there.
Using Apple's official Keychainitemwrapper or sfhfkeychainutils is handy, and then seeing the iphone using Keychain to access the username and password is a great help for understanding keychain, So the arc-control also tried one.
Need to import Security.framework
@implementation Wqkeychain + (nsmutabledictionary *) Getkeychainquery: (NSString *) Service {return [nsmutabledicti Onary Dictionarywithobjectsandkeys: (__bridge_transfer ID) Ksecclassgenericpassword, (__bridge_transfer ID) kSecC Lass, service, (__bridge_transfer ID) ksecattrservice, service, (__bridge_transfer ID) ksecattraccou
NT, (__bridge_transfer ID) ksecattraccessibleafterfirstunlock, (__bridge_transfer ID) ksecattraccessible,
NIL]; } + (void) Save: (NSString *) service data: (ID) data {//get Search dictionary Nsmutabledictionar
Y *keychainquery = [self getkeychainquery:service];
Delete old item before add New Item Secitemdelete ((__bridge_retained cfdictionaryref) keychainquery); Add new object to search dictionary (attention:the data format) [Keychainquery Setobject:[nskeyedarchiver Archive Ddatawithrootobject:data] Forkey: (__bridge_transfer ID) ksecvaluedata];
ADD item to keychain with the search dictionary secitemadd (__bridge_retained cfdictionaryref) keychainquery
, NULL);
} + (ID) Load: (NSString *) Service {ID ret = nil;
Nsmutabledictionary *keychainquery = [self getkeychainquery:service]; Configure the search setting [Keychainquery setobject: (ID) kcfbooleantrue Forkey: (__bridge_transfer ID) ksecreturn
Data];
[Keychainquery setobject: (__bridge_transfer ID) ksecmatchlimitone forkey: (__bridge_transfer ID) kSecMatchLimit];
Cfdataref keyData = NULL;
if (secitemcopymatching (__bridge_retained cfdictionaryref) keychainquery, (Cftyperef *) &keydata) = = NOERR) {
@try {ret = [nskeyedunarchiver unarchiveobjectwithdata: (__bridge_transfer NSData *) KeyData];
} @catch (NSException *e) {NSLog (@ "Unarchive of%@ failed:%@", service, E);
@finally {}} return ret; }
+ (void) Delete: (NSString *) Service {nsmutabledictionary *keychainquery = [Self getkeychainquery:service
];
Secitemdelete ((__bridge_retained cfdictionaryref) keychainquery); } @end