簡單實現KeyChain實例

目錄結構如下:

AppDelegate.m

 1 //
 2 //  AppDelegate.m
 3 //  KeyChain
 4 //
 5 //  Created by apple on 14-12-26.
 6 //  Copyright (c) 2014年 ll. All rights reserved.
 7 //
 8 
 9 #import "AppDelegate.h"
10 
11 @interface AppDelegate ()
12 
13 @end
14 
15 @implementation AppDelegate
16 
17 
18 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
19     // Override point for customization after application launch.
20     ViewController *vc = [[ViewController alloc] init];
21     self.window.rootViewController = vc;
22     [self.window makeKeyAndVisible];
23     return YES;
24 }
25 
26 - (void)applicationWillResignActive:(UIApplication *)application {
27     // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
28     // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
29 }
30 
31 - (void)applicationDidEnterBackground:(UIApplication *)application {
32     // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
33     // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
34 }
35 
36 - (void)applicationWillEnterForeground:(UIApplication *)application {
37     // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
38 }
39 
40 - (void)applicationDidBecomeActive:(UIApplication *)application {
41     // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
42 }
43 
44 - (void)applicationWillTerminate:(UIApplication *)application {
45     // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
46 }
47 
48 @end

KeyChain.h

 1 //
 2 //  KeyChain.h
 3 //  KeyChain
 4 //
 5 //  Created by apple on 14-12-26.
 6 //  Copyright (c) 2014年 ll. All rights reserved.
 7 //
 8 
 9 #import <Foundation/Foundation.h>
10 #import <Security/Security.h>
11 
12 @interface KeyChain : NSObject
13 
14 + (NSMutableDictionary *)newSearchDictionary:(NSString *)identifier;
15 
16 + (void)save:(NSString *)service data:(id)data;
17 
18 + (id)load:(NSString *)service;
19 
20 + (void)delete:(NSString *)service;
21 
22 @end

KeyChain.m

 1 //
 2 //  KeyChain.m
 3 //  KeyChain
 4 //
 5 //  Created by apple on 14-12-26.
 6 //  Copyright (c) 2014年 ll. All rights reserved.
 7 //
 8 /**
 9  *__bridge_transfer , __bridge_retained c和oc類型之間轉換,,可統一使用__bridge替換
10  */
11 #import "KeyChain.h"
12 static NSString *serviceName = @"com.mycompany.myAppServiceName";
13 
14 @implementation KeyChain
15 
16 + (NSMutableDictionary *)newSearchDictionary:(NSString *)identifier
17 {
18     
19     NSMutableDictionary * searchDictionary = [[NSMutableDictionary alloc] init];
20     NSData *encodeInditifier = [identifier dataUsingEncoding:NSUTF8StringEncoding];
21     [searchDictionary setObject:(__bridge_transfer id)kSecClassGenericPassword
22                          forKey:(__bridge_transfer id)kSecClass];
23     [searchDictionary setObject:encodeInditifier forKey:(__bridge_transfer id)kSecAttrGeneric];
24     [searchDictionary setObject:encodeInditifier forKey:(__bridge_transfer id)kSecAttrAccount];
25     [searchDictionary setObject:(__bridge_transfer id)kSecAttrAccessibleAfterFirstUnlock
26                          forKey:(__bridge_transfer id)kSecAttrAccessible];
27     
28     //[searchDictionary setObject:serviceName forKey:(__bridge id)kSecAttrService];
29     
30     return searchDictionary;
31 }
32 
33 +(void)save:(NSString *)service data:(id)data
34 {
35     NSMutableDictionary *keyChainQuery = [self newSearchDictionary:service];
36     /**
37      *  delete old
38      */
39     SecItemDelete((__bridge_retained CFDictionaryRef)keyChainQuery);
40     [keyChainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data]
41                       forKey:(__bridge_transfer id)kSecValueData];
42     /**
43      *  add new
44      */
45     SecItemAdd((__bridge_retained CFDictionaryRef)keyChainQuery, nil);
46     
47 }
48 
49 +(id)load:(NSString *)service
50 {
51     id ret = nil;
52     NSMutableDictionary *keyChainQuery = [self newSearchDictionary:service];
53     [keyChainQuery setObject:(id)kCFBooleanTrue
54                       forKey:(__bridge_transfer id)kSecReturnData];
55     [keyChainQuery setObject:(__bridge_transfer id)kSecMatchLimitOne
56                       forKey:(__bridge_transfer id)kSecMatchLimit];
57     CFDataRef keyData = NULL;
58     
59     if (SecItemCopyMatching((__bridge_retained CFDictionaryRef)keyChainQuery, (CFTypeRef*)&keyData) == noErr)
60     {
61         ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge_transfer NSData*)keyData];
62     }
63     
64 //    if (keyData) {
65 //        
66 //        CFRelease(keyData);
67 //    }
68 //    
69     
70     return ret;
71 }
72 
73 +(void)delete:(NSString *)service
74 {
75     NSMutableDictionary *keyChainQuery = [self newSearchDictionary:service];
76     
77     SecItemDelete((__bridge_retained CFDictionaryRef)keyChainQuery);
78     
79 }
80 
81 
82 @end

ViewController.h

 1 //
 2 //  ViewController.h
 3 //  KeyChain
 4 //
 5 //  Created by apple on 14-12-26.
 6 //  Copyright (c) 2014年 ll. All rights reserved.
 7 //
 8 
 9 #import <UIKit/UIKit.h>
10 #import "KeyChain.h"
11 
12 @interface ViewController : UIViewController
13 
14 + (void)savePassWord:(NSString *)password;
15 
16 + (id)readPassWord;
17 
18 + (void)deletePassWord;
19 
20 
21 @end

?

ViewController.m

  1 //
  2 //  ViewController.m
  3 //  KeyChain
  4 //
  5 //  Created by apple on 14-12-26.
  6 //  Copyright (c) 2014年 ll. All rights reserved.
  7 //
  8 
  9 #import "ViewController.h"
 10 static NSString * const KEY_IN_KEYCHAIN = @"com.wuqian.app.allinfo";// 字典在keychain中的key
 11 static NSString * const KEY_PASSWORD = @"com.wuqian.app.password"; //  密碼在字典中的key
 12 
 13 @interface ViewController ()
 14 {
 15     UITextField * _field; // 輸入密碼
 16     UILabel *_psw;        // 顯示密碼
 17 }
 18 
 19 @end
 20 
 21 @implementation ViewController
 22 
 23 - (void)viewDidLoad {
 24     [super viewDidLoad];
 25     
 26     self.view.backgroundColor = [UIColor whiteColor];
 27     
 28     UILabel * labelName = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, 100, 30)];
 29     labelName.text = @"密碼是:";
 30     
 31     
 32     _field = [[UITextField alloc] initWithFrame:CGRectMake(100, 80, 200, 30)];
 33     _field.placeholder = @"請輸入密碼";
 34     _field.borderStyle = UITextBorderStyleRoundedRect;
 35     
 36     _psw = [[UILabel alloc] initWithFrame:CGRectMake(100, 30, 200, 30)];
 37     _psw.backgroundColor = [UIColor yellowColor];
 38 
 39     UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
 40     btn.frame =CGRectMake(100, 160, 200, 30);
 41     btn.backgroundColor = [UIColor colorWithRed:0 green:0.4 blue:0.1 alpha:0.8];
 42     btn.tintColor = [UIColor redColor];
 43     [btn setTitle:@"submit" forState:UIControlStateNormal];
 44     //[btn setTitle:@"正在提交" forState:UIControlStateSelected];
//btn.layer.cornerRadius=8; 圓角
??? //btn.layer.masksToBounds = YES;
?? //btn.layer.borderWidth = 5;
??? //btn.layer.borderColor=(__bridge CGColorRef)([UIColor redColor]);
45 46 [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside]; 47 // UIGestureRecognizer *tap = [[UIGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)]; 48 // [self.view addGestureRecognizer:tap]; 49 50 51 52 [self.view addSubview:btn]; 53 [self.view addSubview:_field]; 54 [self.view addSubview:labelName]; 55 [self.view addSubview:_psw]; 56 // Do any additional setup after loading the view, typically from a nib. 57 } 58 59 - (void)didReceiveMemoryWarning { 60 [super didReceiveMemoryWarning]; 61 // Dispose of any resources that can be recreated. 62 } 63 //- (void)tap:(UIGestureRecognizer*)gr 64 //{ 65 // 66 // 67 // [_field resignFirstResponder]; 68 //} 69 70 - (void)btnClick:(id)sender 71 { 72 [ViewController savePassWord:_field.text]; 73 _psw.text = [ViewController readPassWord]; 74 75 if (![_field isExclusiveTouch]) { 76 //Setting this property to YES causes the receiver to block the delivery of touch events to other views in the same window. The default value of this property is NO. 77 [_field resignFirstResponder];// 收回鍵盤 78 79 } 80 81 } 82 83 + (void)savePassWord:(NSString *)password 84 { 85 NSMutableDictionary *usernamepasswordKVPairs = [[NSMutableDictionary alloc] init]; 86 [usernamepasswordKVPairs setObject:password forKey:KEY_PASSWORD]; 87 [KeyChain save:KEY_IN_KEYCHAIN data:usernamepasswordKVPairs]; 88 } 89 90 + (id)readPassWord 91 { 92 NSMutableDictionary *usernamepasswordKVPairs = (NSMutableDictionary *)[KeyChain load:KEY_IN_KEYCHAIN]; 93 94 return [usernamepasswordKVPairs objectForKey:KEY_PASSWORD]; 95 96 } 97 98 + (void)deletePassWord 99 { 100 [KeyChain delete:KEY_IN_KEYCHAIN]; 101 102 } 103 104 @end

運行效果:

轉載于:https://www.cnblogs.com/liuziyu/p/4191332.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/259565.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/259565.shtml
英文地址,請注明出處:http://en.pswp.cn/news/259565.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Oracle 建立包 和 包體

--創建包create or replace package pac_stuastype cur_stu is ref cursor;procedure getStu(i in number,cur_stu out cur_stu);end pac_stu;--創建包體create or replace package body pac_stuasprocedure getStu(i in number,cur_stu out cur_stu)asnums number(10);begins…

alibaba fastjson

JSON解析器fastjson&#xff08;阿里巴巴出品&#xff0c;版本1.1.33&#xff09; import com.alibaba.fastjson.JSON; public static final Object parse(String text); // 把JSON文本parse為JSONObject或者JSONArraypublic static final JSONObject parseObject(String text)…

matlab 讀取excel一列,讀取excel中的數據把第一列相同的所有行數據輸出成一個excel...

該樓層疑似違規已被系統折疊 隱藏此樓查看此樓284 1113436773300.00 1113436773.30 44.55284 1113436773400.00 1113436773.40 44.55284 1113436773500.00 1113436773.50 44.55284 1113436773600.00 1113436773.60 44.55284 1113436773700.00 1113436773.70 43.77284 111343677…

js function理解

1.function是對象&#xff0c;定義一個function就會在堆中創建一個對象。生成函數如下&#xff1a; (1) var a new Function("document.write(1)"); (2) var a function(){document.write(1);} (3) function a(){ document.write(1); } (4) (function(){ document.…

鍋巴H264播放器地址和說明

鍋巴H264播放器地址和說明 軟件說明: 此工具專門用來播放安防監控行業的H264錄像文件,不管是哪個設備廠家的視頻協議,只要您的錄像文件里有 H264數據,就可以播放. 備注: 因為被一些事情的影響,本來做好了很多的功能, 猶豫很長時間,還是去掉了,這個播放器僅僅是演示我們的解碼器…

poj2431 Expedition

直接代碼、、、 #include<string.h> #include<stdio.h> #include<queue> #include<iostream> #include<algorithm> using namespace std; struct node {int fuel,dist;//bool operator < (const node&d) const{// return dist>d.dist…

JAVA入門[6]-Mybatis簡單示例

初次使用Mybatis,先手寫一個hello world級別的例子&#xff0c;即根據id查詢商品分類詳情。 一、建表 create table Category ( Id INT not null, Name varchar(80) null, constraint pk_category primary key (Id) ); 插入測試數據 INSERT INTO category VALUES (1,Fish); INS…

qpsk調制matlab實現,QPSK調制解調Matlab實現(ing待補充說明)

自寫%QPSKclose all;clc;%思路&#xff1a;1.輸入一組隨機初始信息x[01矩陣]&#xff1b;% 2.按兩兩一組通過for循環判別4種組合&#xff0c;分別對應星座圖4個點% 3.做星座圖% a.過程中考慮過將01序列兩兩分開表示出來&#xff0c;不知是否有必要&#xff0c;未實現% b.考慮兩…

猴子吃桃問題(南陽ACM324)

猴子吃桃問題 時間限制&#xff1a;3000 ms | 內存限制&#xff1a;65535 KB難度&#xff1a;0描述有一堆桃子不知數目&#xff0c;猴子第一天吃掉一半&#xff0c;又多吃了一個&#xff0c;第二天照此方法&#xff0c;吃掉剩下桃子的一半又多一個&#xff0c;天天如此&#…

ASP.NET MVC5 + EF6 入門教程 (6) View中的Razor使用

ASP.NET MVC5 EF6 入門教程 (6) View中的Razor使用 原文:ASP.NET MVC5 EF6 入門教程 (6) View中的Razor使用文章來源&#xff1a; Slark.NET-博客園 http://www.cnblogs.com/slark/p/mvc-5-ef-6-get-started-model.html 上一節&#xff1a;ASP.NET MVC5 EF6 入門教程 (5) M…

matlab中求三維中的多個體積,用matlab計算由下面2個幾何體圍成的體積: x^2+y^2+z^2=36,((x-4)/5)^2+((y-1)/3)^2+((z-2)/5)^2=1...

答&#xff1a;>> triplequad((x,y,z)1*(x.^2y.^2z.^2答&#xff1a;首先建立一個m文件 我取的名字叫 syfs0000 function ysyfs0000(x) y[9*x(1)^236*x(2)^24*x(3)^2-36; x(1)^2-2*x(2)^2-20*x(3); 16*x(1)-x(1)^3-2*x(2)^2-16*x(3)^2;]; end 然后在command window 輸入 …

分析分布式服務框架

出處&#xff1a;http://www.cnblogs.com/zhangs1986/ 技術是為需求而服務的&#xff0c;分布式服務框架也同樣如此&#xff0c;它不是憑空誕生的&#xff0c;也是因為有這樣的需求才會有分布式服務框架這么樣的東西誕生&#xff0c;在這篇blog中來詳細的分析分布式服務框架誕…

PL/SQL注冊碼

code:j6stndb9tk72xfbhbqczcdqnjd8lyj466n number:882851 ps&#xff1a;xs374ca轉載于:https://www.cnblogs.com/myblogslh/p/4203173.html

遞歸--基于回溯和遞歸的八皇后問題解法

八皇后問題是在8*8的棋盤上放置8枚皇后&#xff0c;使得棋盤中每個縱向、橫向、左上至右下斜向、右上至左下斜向均只有一枚皇后。八皇后的一個可行解如圖所示&#xff1a; 思路 對于八皇后的求解可采用回溯算法&#xff0c;從上至下依次在每一行放置皇后&#xff0c;進行搜索&a…

matlab emf 讀取,20140219-Emf_Demo EMF 矢量圖 可以讀取和保存EMF 的封閉類 非常實用 matlab 238萬源代碼下載- www.pudn.com...

文件名稱: 20140219-Emf_Demo下載收藏√ [5 4 3 2 1 ]開發工具: Visual C文件大小: 6312 KB上傳時間: 2014-07-10下載次數: 2詳細說明&#xff1a;EMF 矢量圖 可以讀取和保存EMF矢量圖的封閉類非常實用-EMF EMF vector can read and save the class very useful vector cl…

orcale 之 集合操作

集合操作就是將兩個或者多個 sql 查詢的結果合并成復合查詢。常見的集合操作有UNION(并運算)、UNION ALL、INTERSECT(交運算)和MINUS(差運算)。 UNION UNION 運算可以將多個查詢結果集相加,形成一個結果集, 其結果相當于集合運算的并運算. UNION 可以將第一個查詢結果的所有行與…

PDFMate PDF Converter Pro

http://www.pdfmate.com轉載于:https://www.cnblogs.com/scgw/p/4203999.html

linux 廣播

廣播是一臺主機向局域網內的所有主機發送數據。這時&#xff0c;同一網段的所有主機都能接收到數據。發送廣播包的步驟大致如下: (1)確定一個發送廣播的接口&#xff0c;如eth0 (2)確定廣播的地址&#xff0c;通過ioctl函數&#xff0c;請求碼設置為SIOCGIFBRDADDR得到廣播的地…

thinkphp5.1 php7,空白目錄 · 細數ThinkPHP5.1.7版本新特性 · 看云

>[danger] 官方已經在前不久發布了ThinkPHP5.1.7版本&#xff0c;5.1版本相較于5.0版本而言&#xff0c;本身更加嚴謹和規范&#xff0c;更接近主流設計思想。近半年來&#xff0c;5.1版本更新頻繁&#xff0c;此次最新版本更是帶來了很多的新特性。正在或者打算使用5.1版本…

JS中popup.js

為什么80%的碼農都做不了架構師&#xff1f;>>> //popup class 顯示彈出窗口&#xff0c;。/*以下為使用popup對象&#xff0c;傳入相應的配置參數&#xff0c;彈出不同類型的窗口 function ShowIframe() //顯示iframe { var popnew P…