IOS uses keychain for simple access to the user name and password during login Registration

Source: Internet
Author: User

During simple login and registration interface design, users often encounter access design issues with user names and passwords. Other solutions are not discussed here. Now we will introduce a relatively simple method-keychain.

You can find the keychain, keychainitemwrapper. H, and keychainitemwrapper. M files in the generickeychain instance.

But now we only need to perform simple user name and password access operations. We only need to write a class by ourselves. The Code is as follows (from the Internet)

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

Note:

I. introduce several strings to do this.

Here I Get A keychainfile class:

The keychainfile. h file is as follows:

// The key value of the user name and password. the user name and password are stored in the keychain. Extern nsstring * const key_username_password; extern nsstring * const key_username; extern nsstring * const key_password;

The keychainkey. M file is as follows:

#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";

2. Import # import <Security/security. h> In the chkeychain. h file and add this security. Framework to the target file.

3. If you directly add the above files in the project using arc, an error may occur because the chkeychain. M file does not have the arc feature, so add arc to chkeychain. M. Specifically, select "build phases" on the right of the target and find "compile sources. Double-click the file to add the arc feature and add the:-fno-objc-arc parameter.

(Appendix:Introduce a file that uses the arc feature in a project that does not use the arc feature: add the-fobjc-arc parameter to the file.)


Usage:

1. Define a user

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

2. Save

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

3. Use

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

4. Delete

[CHKeychain delete:KEY_USERNAME_PASSWORD];

OK. The introduction is complete.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.