Reference: HTTP://WWW.JIANSHU.COM/P/F6D40065BB6C
#import <Foundation/Foundation.h> #import <Security/Security.h> @interface jckeychaintool:nsobject/** * save string to?? Keychain * * @param svalue corresponding value * @param sKey corresponding key */+ (void) Savekeychainvalue: (NSString *) svalue key: ( NSString *) skey;/** * from?? The keychain gets the string * * @param sKey corresponding key * * @return returns the stored value */+ (NSString *) Readkeychainvalue: (NSString *) skey;/** *
from?? Keychain Delete String * * @param sKey corresponding key */+ (void) Deletekeychainvalue: (NSString *) SKey; @end
#import "JCKeychainTool.h" @implementation jckeychaintool+ (Nsmutabledictionary *) Getkeychainquery: (NSString *) service{return [nsmutabledictionary Dictionarywithobjectsandkeys: (__bridge_transfer ID) ksecclassgenericpas Sword, (__bridge_transfer id) ksecclass,service, (__bridge_transfer ID) ksecattrservice,service, (__bridge_transfer ID) ksecattraccount, (__bridge_transfer ID) ksecattraccessibleafterfirstunlock, (__bridge_transfer ID) ksecattraccessible, nil];} + (void) Savekeychainvalue: (NSString *) svalue key: (NSString *) skey{nsmutabledictionary * keychainquery = [self getKeych Ainquery:skey]; Secitemdelete ((__bridge_retained cfdictionaryref) keychainquery); [Keychainquery setobject:[nskeyedarchiver Archiveddatawithrootobject:svalue] Forkey: (__bridge_transfer ID) Ksecvaluedata]; Secitemadd ((__bridge_retained cfdictionaryref) keychainquery, NULL); }+ (NSString *) Readkeychainvalue: (NSString *) SKey{NSString *ret = nil; Nsmutabledictionary *keychainquery = [self getkeychainquery:skey]; [Keychainquery setobject: (ID) kcfbooleantrue Forkey: (__bridge_transfer ID) ksecreturndata]; [Keychainquery setobject: (__bridge_transfer ID) ksecmatchlimitone forkey: (__bridge_transfer ID) kSecMatchLimit]; Cfdataref keyData = NULL; if (secitemcopymatching (__bridge cfdictionaryref) keychainquery, (Cftyperef *) &keydata) = = NOERR) {@try { RET = (NSString *) [Nskeyedunarchiver unarchiveobjectwithdata: (__bridge NSData *) KeyData]; } @catch (NSException *e) {NSLog (@ "Unarchive of%@ failed:%@", SKey, E); } @finally {}} if (KeyData) cfrelease (keyData); return ret;} + (void) Deletekeychainvalue: (NSString *) SKey {nsmutabledictionary *keychainquery = [self getkeychainquery:skey]; Secitemdelete ((__bridge cfdictionaryref) keychainquery);} @end
Save [jckeychaintool savekeychainvalue:@ "xxx" key:@ "userName"]; [Jckeychaintool savekeychainvalue:@ "yyy" key:@ "password"];//read [Jckeychaintool readkeychainvalue:@ "UserName"]; [Jckeychaintool readkeychainvalue:@ "password"];//delete [Jckeychaintool deletekeychainvalue:@ "UserName"]; [Jckeychaintool deletekeychainvalue:@ "password"];
IOS Keychain Stores user data