SSKeyChains對apple平安框架API停止了復雜封裝,支持對存儲在鑰匙串中密碼、賬戶停止訪問,包括讀取、刪除和設置;
在工程中參加SSKeyChain
在工程中參加Security.framework框架。把SSKeychain.h和SSKeychain.m加到項目文件夾。
運用SSKeyChain
經過以下類辦法來運用SSKeyChain(請檢查SSKeyChain.h):
+ (NSArray *)allAccounts; + (NSArray *)accountsForService:(NSString *)serviceName; + (NSString *)passwordForService:(NSString *)serviceName account:(NSString *)account; + (BOOL)deletePasswordForService:(NSString *)serviceName account:(NSString *)account; + (BOOL)setPassword:(NSString *)password forService:(NSString *)serviceName account:(NSString *)account;==Demo
#import "SSKeychain.h" static NSString *kSSToolkitTestsServiceName = @"SSToolkitTestService"; static NSString *kSSToolkitTestsAccountName = @"SSToolkitTestAccount"; static NSString *kSSToolkitTestsPassword = @"SSToolkitTestPassword"; @interface SSKeychainTests : SenTestCase - (BOOL)_accounts:(NSArray *)accounts containsAccountWithName:(NSString *)name; @end
@implementation SSKeychainTests - (void)testAll { //留意:setPassword 就是詳細要存儲的值 // Getting & Setings Passwords //設置密碼和賬戶名 [SSKeychain setPassword:@"123" forService:kSSToolkitTestsServiceName account:kSSToolkitTestsAccountName]; //獲取密碼 NSString *password = [SSKeychain passwordForService:kSSToolkitTestsServiceName account:kSSToolkitTestsAccountName]; NSLog(@"%@",password); STAssertEqualObjects(password, @"123", @"Password reads and writes"); NSLog(@"============"); // Getting Accounts //獲取一切賬號 NSArray *accounts = [SSKeychain allAccounts]; STAssertTrue([self _accounts:accounts containsAccountWithName:kSSToolkitTestsAccountName], @"All accounts"); NSLog(@"==11==%@",accounts); //獲取以後服務下的賬號名 accounts = [SSKeychain accountsForService:kSSToolkitTestsServiceName]; NSLog(@"==22==%@",accounts); STAssertTrue([self _accounts:accounts containsAccountWithName:kSSToolkitTestsAccountName], @"Account for service"); // Deleting Passwords //刪除以後賬戶的密碼 [SSKeychain deletePasswordForService:kSSToolkitTestsServiceName account:kSSToolkitTestsAccountName]; //獲取以後賬號的密碼 password = [SSKeychain passwordForService:kSSToolkitTestsServiceName account:kSSToolkitTestsAccountName]; STAssertNil(password, @"Password deletes"); } - (BOOL)_accounts:(NSArray *)accounts containsAccountWithName:(NSString *)name { for (NSDictionary *dictionary in accounts) { if ([[dictionary objectForKey:@"acct"] isEqualToString:name]) { return YES; } } return NO; }
假如你保管密碼失敗,會有這樣的提示:
NSError *error = nil; NSString *password = [SSKeychain passwordForService:@"MyService" account:@"samsoffes" error:&error]; if ([error code] == SSKeychainErrorNotFound) { NSLog(@"Password not found"); }
【xcode iOS 本地保管密碼 SSKeyChain】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!