由于苹果最近有了一些新动作,所以keychain这个功能可能没有办法做到iOS删除App也无法删除的数据
,具体的内容可以看我最新的文章iOS 10.3 keychain 功能可能出现重大更改。
看标题是不是听起来挺唬人的,没错就是这么唬人,之前我没有发现iOS有这个功能,但是装了几个百度的应用之后我发现:卸载百度的应用之后,过段时间再次安装的时候你就会发现百度账号自动登录了,没错你可以去试试。看到这个现象之后我就寻求实现方法。下面贴出来:
iOS的keychain服务提供了一种安全的保存私密信息(密码,序列号,证书等)的方式。每个ios程序都有一个独立的keychain存储。从ios 3.0开始,跨程序分享keychain变得可行。
下面就使用keychain来实现存取用户名和密码。
苹果已经有现成的类封装好了keychain,KeychainItemWrapper.h和KeychainItemWrapper.m文件,可以在GenericKeychain实例里找到。
但是这里我只需要存取用户名和密码,就不用苹果提供的类了,自己写个简单的类来实现就好。
代码如下:
HPKeychain.h
#import <Foundation/Foundation.h>
@interface HPKeychain : NSObject
+ (void)save:(NSString *)service data:(id)data;
+ (id)load:(NSString *)service;
+ (void)delete:(NSString *)service;
@end
HPKeychain.m
#import "HPKeychain.h"
@implementation HPKeychain
+ (NSMutableDictionary *)getKeychainQuery:(NSString *)service {
return [NSMutableDictionary dictionaryWithObjectsAndKeys:
(id)kSecClassGenericPassword,(id)kSecClass,
service, (id)kSecAttrService,
service, (id)kSecAttrAccount,
(id)kSecAttrAccessibleAfterFirstUnlock,(id)kSecAttrAccessible,
nil];
}
+ (void)save:(NSString *)service data:(id)data {
//Get search dictionary
NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
//Delete old item before add new item
SecItemDelete((CFDictionaryRef)keychainQuery);
//Add new object to search dictionary(Attention:the data format)
[keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(id)kSecValueData];
//Add item to keychain with the search dictionary
SecItemAdd((CFDictionaryRef)keychainQuery, NULL);
}
+ (id)load:(NSString *)service {
id ret = nil;
NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
//Configure the search setting
//Since in our simple case we are expecting only a single attribute to be returned (the password) we can set the attribute kSecReturnData to kCFBooleanTrue
[keychainQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];
[keychainQuery setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];
CFDataRef keyData = NULL;
if (SecItemCopyMatching((CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) {
@try {
ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)keyData];
} @catch (NSException *e) {
NSLog(@"Unarchive of %@ failed: %@", service, e);
} @finally {
}
}
if (keyData)
CFRelease(keyData);
return ret;
}
+ (void)delete:(NSString *)service {
NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
SecItemDelete((CFDictionaryRef)keychainQuery);
}
@end
使用方法
#import "ViewController.h"
#import "HPKeychain.h"
NSString * const KEY_USERNAME_PASSWORD = @"com.company.app.usernamepassword";
NSString * const KEY_USERNAME = @"com.company.app.username";
NSString * const KEY_PASSWORD = @"com.company.app.password";
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *nameTextfield;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//从keychain中取出用户名和密码:
NSMutableDictionary *usernamepasswordKVPairs = (NSMutableDictionary *)[HPKeychain load:KEY_USERNAME_PASSWORD];
_nameTextfield.text = [usernamepasswordKVPairs objectForKey:KEY_USERNAME];
_passwordTextField.text = [usernamepasswordKVPairs objectForKey:KEY_PASSWORD];
}
- (IBAction)saveAction:(UIButton *)sender {
//把用户名和密码存入keychain:
NSMutableDictionary *usernamepasswordKVPairs = [NSMutableDictionary dictionary];
[usernamepasswordKVPairs setObject:_nameTextfield.text forKey:KEY_USERNAME];
[usernamepasswordKVPairs setObject:_passwordTextField.text forKey:KEY_PASSWORD];
[HPKeychain save:KEY_USERNAME_PASSWORD data:usernamepasswordKVPairs];
UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"保存成功" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction * action = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"点击了确认");
}];
[alert addAction:action];
[self presentViewController:alert animated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
删除一个keychain item:
[HPKeychain delete:KEY_USERNAME_PASSWORD];
这里可以查看代码
网友评论