ios KeyChain项目中应用到的内容

太叔昊苍
2023-12-01

.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

.m

#import "CHKeyChain.h"

 

@implementation CHKeyChain

 

+ (NSMutableDictionary *)getKeychainQuery:(NSString *)service {  

    return [NSMutableDictionarydictionaryWithObjectsAndKeys:  

            (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:[NSKeyedArchiverarchivedDataWithRootObject: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)kSecMatchLimitOneforKey:(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);  

}  

 

调用类,使用方法:

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

 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

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

//    txtfldUsername.text = [usernamepasswordKVPairs objectForKey:KEY_USERNAME];  

//    txtfldPassword.text = [usernamepasswordKVPairs objectForKey:KEY_PASSWORD];  

    if (indexPath.section == 0) {

        static NSString *TableViewCell = @"TableViewCell"

        UITableViewCell *cell = [tableView

                                 dequeueReusableCellWithIdentifier: TableViewCell]; 

        if (cell == nil) { 

            cell = [[[UITableViewCell alloc

                    initWithStyle:UITableViewCellStyleDefault

                    reuseIdentifier: TableViewCell] autorelease]; 

        } 

        

//        for (UIView * v in [cell.contentView subviews]) {

//            [v removeFromSuperview];

//        }

        

        NSUInteger row = [indexPath row]; 

        NSString *title = [nameList objectAtIndex:row];

        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 80, 42)];

        [label setText:title];

        [label setBackgroundColor:[UIColorclearColor]];

        [cell.contentView addSubview:label];

        if (row==0) {

            //user name

            if (self.mNameField == NULL) {

                UITextField *content = [[UITextField alloc]initWithFrame:CGRectMake(80, 10, 220, 30)];

                [content setBackgroundColor:[UIColor clearColor]];

                content.delegate = self;

                content.text = [usernamepasswordKVPairs objectForKey:KEY_USERNAME]; 

                content.clearButtonMode = UITextFieldViewModeAlways;

                self.mNameField = content;

                [content release];

            }

            [cell.contentView addSubview:self.mNameField];

        }else if ( row == 1){

            //password

            if (self.mPasswordField == NULL) {

                UITextField *content = [[UITextField alloc]initWithFrame:CGRectMake(80, 10, 220, 30)];

                [content setBackgroundColor:[UIColor clearColor]];

                content.secureTextEntry = YES;

                content.delegate = self;

                content.text = [usernamepasswordKVPairs objectForKey:KEY_PASSWORD];  

                content.clearButtonMode = UITextFieldViewModeAlways;

                self.mPasswordField = content;

                [content release];

            }

            [cell.contentView addSubview:self.mPasswordField];

        }

        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        [label release];                                                                                                                                                                                                                                                                                                                                                                                                                                                                             

        return cell; 

    }

    static NSString *CellIdentifier = @"Cell";          

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];  

    if (cell == nil) {  

        cell = [[UITableViewCellalloc] initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:CellIdentifier]; 

    }  

    NSString *title = @"注册成为海航用户";

    cell.textLabel.text = title;

    cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;

    return cell;

}

 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    if (nil != BusyAlert)

        [BusyAlertdismissWithClickedButtonIndex:0animated:YES];

    downloadedBytes = totalBytes;

    NSLog(@"connectionDidFinishLoading");

    NSString *tempString = [[NSStringalloc] initWithData: downloadedDataencoding:NSUTF8StringEncoding];

    NSLog(@"tempString:%@",tempString);

 

    NSMutableDictionary *dic = [tempString JSONValue];

    NSLog(@"dic:%@",dic);

    if ([[dic allKeys] containsObject:@"access_token"]) {

        [CHKeyChaindelete:KEY_USERNAME_PASSWORD];

        NSString *partnerCodeString = [NSString stringWithFormat:@"%@",[dic objectForKey:@"access_token"]];

        self.flagToken = partnerCodeString;

        NSLog(@"self.flagToken:%@",self.flagToken);

        NSMutableDictionary *usernamepasswordKVPairs = [NSMutableDictionary dictionary];  

        [usernamepasswordKVPairs setObject:mNameField.text forKey:KEY_USERNAME];  

        [usernamepasswordKVPairs setObject:mPasswordField.text forKey:KEY_PASSWORD];  

        [CHKeyChain save:KEY_USERNAME_PASSWORD data:usernamepasswordKVPairs];  

        AccountCenterViewController * accountcenter = [[AccountCenterViewControlleralloc] init];

        [self.navigationController pushViewController:accountcenter animated:YES];

    }

    else {

        NSString *partnerCodeString = [NSString stringWithFormat:@"%@",[dic objectForKey:@"error"]];

        UIAlertView* alert = [[UIAlertViewalloc] initWithTitle:@"提示"message:partnerCodeString delegate:nilcancelButtonTitle:@"OK"otherButtonTitles:nil, nil];

        [alert show];

        [alert release];

    }

    downloadedData = nil;

}

http://www.cnblogs.com/zhengyn/archive/2012/08/29/2662657.html#top
 类似资料: