iOS 在登陆注册中使用keychain进行简单的存取用户名和密码

    在进行简单的登陆注册界面设计中往往都会遇到用户名和密码的存取设计问题,在此暂不讨论其他解决方法,现在介绍一种相对简单的方式--keychain。

苹果已经有现成的类封装好了keychain,KeychainItemWrapper.h和KeychainItemWrapper.m文件,可以在GenericKeychain实例里找到。

但是现在只是进行简单的存取用户名和密码操作,只需要自己写一个类;代码如下(来自网上)

CHkeychain.h :

#import <Foundation/Foundation.h>
#import <Security/Security.h>

@interface CHKeychain : NSObject

+ (void)save:(NSString *)service data:(id)data;
+ (id)load:(NSString *)service;
+ (void)delete:(NSString *)service;

@end


CHkeychain.m


#import "CHKeychain.h"

@implementation CHKeychain
+ (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:(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

注意事项:

一、还要引入几个字符串来做可以

我这里弄了一个类keychainfile:

keychainfile.h文件如下:

//用户名和密码保存的key值,用户名和密码保存在keychain中。
extern NSString * const KEY_USERNAME_PASSWORD;
extern NSString * const KEY_USERNAME;
extern NSString * const KEY_PASSWORD;

keychainkey.m文件如下:

#import "keychainfile.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";

二、注意要在CHkeychain.h文件中导入 #import <Security/Security.h> 而且要在target中添加这个Security.framework


三、在使用了ARC的工程中直接添加以上文件,可能会出现ARC报错,原因就是CHkeychain.m文件没有ARC特性,那么就对CHkeychain.m添加ARC。具体就是在target中选中右侧的“Build Phases”,向下就找到“Compile Sources”了。双击要添加arc特性的文件,添加:-fno-objc-arc参数。

(附:在未使用arc的工程中引入一个使用了arc特性的文件:对相应的文件添加:-fobjc-arc参数


用法:

1、定义一个用户

NSMutableDictionary *usernamepasswordKVPairs = (NSMutableDictionary *)[CHKeychain load:KEY_USERNAME_PASSWORD];

2、保存

[usernamepasswordKVPairs setObject:userName.text forKey:KEY_USERNAME];
[usernamepasswordKVPairs setObject:passWord.text forKey:KEY_PASSWORD];
[CHKeychain save:KEY_USERNAME_PASSWORD data:usernamepasswordKVPairs];

3、使用

usernamepasswordKVPairs = (NSMutableDictionary *)[CHKeychain load:KEY_USERNAME_PASSWORD];

4、删除

[CHKeychain delete:KEY_USERNAME_PASSWORD];

Ok,介绍完毕。




你可能感兴趣的:(iOS 在登陆注册中使用keychain进行简单的存取用户名和密码)