SSKeyChains对苹果安全框架API进行了简单封装,支持对存储在钥匙串中密码、帐户进行访问,包括读取、删除和设置。SSKeyChain的做者是大名鼎鼎的SSToolkit的做者samsoffes。html
项目地址:https://github.com/samsoffes/sskeychaingit
在工程中加入SSKeyChaingithub
在工程中加入Security.framework框架。安全
把SSKeychain.h和SSKeychain.m加到项目文件夹。app
使用SSKeyChain框架
经过如下类方法来使用SSKeyChain(请查看SSKeyChain.h):ui
+ (NSArray *)allAccounts;atom
+ (NSArray *)accountsForService:(NSString *)serviceName;spa
+ (NSString *)passwordForService:(NSString *)serviceNameaccount:(NSString *)account;调试
+ (BOOL)deletePasswordForService:(NSString *)serviceNameaccount:(NSString *)account;
+ (BOOL)setPassword:(NSString *)password forService:(NSString*)serviceName account:(NSString *)account;
文档
在Xcode中安装SSKeyChain的帮助文档须要如下步骤:
打开菜单 Xcode -> Preferences
选择 Downloads
选择 Documentation
点击底部的加号按钮,并输入如下URL: http://docs.samsoff.es/com.samsoffes.sskeychain.atom
点击”SSKeyChain Documentation”旁边的install按钮。 (若是你看不到它,也没有提示任何错误,请重启Xcode)
确保在Organizer中可选的docset中可以看到SSKeychain。
此外,能够在线查看SSKeychain Documentation。
调试
若是没法保存钥匙串,请使用SSKeychain.h中提供的错误代码,例如:
NSError *error = nil;
NSString *password = [SSKeychainpasswordForService:@"MyService" account:@"samsoffes"error:&error];
if ([error code] == SSKeychainErrorNotFound) {
NSLog(@"Passwordnot found");
}
显然,你对作这个应该很熟悉了。访问钥匙串是件痛苦的事情,你要随时检查它的每一个错误和失败。SSKeychain并无使它(钥匙串)变得更稳定,它仅仅是繁琐的C APIs封装。
示例代码
保存一个UUID字符串到钥匙串:
CFUUIDRef uuid = CFUUIDCreate(NULL); assert(uuid != NULL); CFStringRef uuidStr = CFUUIDCreateString(NULL, uuid);
[SSKeychain setPassword: [NSString stringWithFormat:@"%@", uuidStr]
forService:@"com.yourapp.yourcompany"account:@"user"];
而后,从钥匙串读取UUID:
NSString *retrieveuuid = [SSKeychainpasswordForService:@"com.yourapp.yourcompany"account:@"user"];
注意: setPassword和passwordForSevice方法中的services 和 accounts 参数应该是一致的。