Original blog, reproduced please indicate the source
Blog.csdn.net/hello_hwc?viewmode=list
Preface: The first two persistence, respectively, talked about
- Nsuserdefaults Saving settings information
- Plist Save Simple Structured information
This article explains how to save information that needs to be encrypted. In most cases, the password is saved. In rare cases, you need to save information such as certificates. This article takes the password as an example to explain how to use the iOS SDK native API for keychain operation.
During the actual development process, it is recommended to use some of the GitHub's integrated libraries, or write a keychain library of your own, very simple
Source code for Swift version, full engineering download
CSDN Download
http://download.csdn.net/detail/hello_hwc/8663811
GitHub
Https://github.com/wenchenhuang/SwiftKeyChainDemo
Demo effect
Four keys corresponding to add, update, GET, delete
The demo's password does not show black dots for easy viewing.
Four types of operation
---get----
Keychain Introduction
Keychain is an encrypted container that is typically used to store passwords, certificates, and keys that require encryption. For iOS, each app has a separate keychain, and each app can only access its own keychain.
Note: The access rights of keychain depend on provisioning file. So, if you want to still be able to access the previously saved password when the update is applied, make sure that the provisioning file is the same.
Keychain Description
Keychain is described by a dictionary, which is a set of key-value pairs. Used to describe what kind of data the keychain is for, what kind of access permissions, and so on.
A typical dictionary.
which
- Ksecclass means that the password is stored
- Ksecattraccount represents the password stored for the Iamuser account.
- Ksecattrservice represents an account stored for the App Store
- The remaining two are used in the query, knowing that if the query is set to Ture, you can
All keys can be obtained from the following links
Https://developer.apple.com/library/ios/documentation/Security/Reference/keychainservices/index.html
Teach you to build a demo app to create a swift-based project, then drag and drop controls on the storyboard
and drag outlet and action, and then implement uitextfielddelegate to ensure that when we click Return, the keyboard disappears. This time the code is as follows
Import Securityclass Viewcontroller:Uiviewcontroller,uitextfielddelegate{ @IboutletWeak Var Usernametextfield:Uitextfield! @IboutletWeak Var Passwordtextfield:Uitextfield! @ibactionFunc Addkeychainitem(sender: anyobject){ } @ibactionFunc Updatekeychainitem(sender: anyobject){ } @ibactionFunc Getkeychainitem(sender: anyobject){ } @ibactionFunc Deletekeychainitem(sender: anyobject){} override Func Viewdidload(){Super.viewdidload()Usernametextfield.delegate = Self passwordtextfield.delegate = self// DoAny additional setup after loading the view, typically from a nib. } func Textfieldshouldreturn(textField: uitextfield)-Bool{Textfield.resignfirstresponder()Return true}}
Then, add a few helper methods to reduce the amount of our code
Create a default description dictionary
func createdefaultkeychainitemdic ()->nsmutabledictionary {var keychainitem = nsmutabledictionary () Keychainitem.setobject (Ksecclassinternetpassword as nsstring , Forkey:ksecclass as nsstring ) Keychainitem.setobject (, Forkey: Ksecattrserver as nsstring ) keychainitem.setObject (self .usernametextfield .text , Forkey:ksecattraccount as nsstring ) return Keychainitem}
Use Uialertcontroller to prompt information
Func Alertwithmessage (message:String) {var Alertcontroller =Uialertcontroller(Title:"Info",message:MessagePreferredstyle: Uialertcontrollerstyle.Alert) Alertcontroller.addaction (uialertaction(Title:"OK",Style: Uialertactionstyle.Cancel,Handler:Nil)) Self. Presentviewcontroller (Alertcontroller,Animated: true,Completion: Nil)} func Alertwithstatus (Status:Osstatus){if(Status = =0){ Self. Alertwithmessage ("Success") }Else{ Self. Alertwithmessage ("Fail ErrorCode is\ (status)") } }
Add Keychain
- Here, use the function secitemcopymatching to find out if this keychain exists. Two parameters, the first is a description of the dictionary, the second is a copy of the search results to the dictionary, usually only when the acquisition of the use, here is nil.
- Ksecvaluedata This key is the actual password to be saved, first converted to NSData
- Secitemadd This function to add keychain, the return value is osstatus type, the error type is more, can Google. Here you know that 0 is no mistake.
@IBActionFunc Addkeychainitem (Sender: Anyobject) {var Keychainitem = Self. Createdefaultkeychainitemdic ()if secitemcopymatching(Keychainitem,Nil) = = noerr{ Self. Alertwithmessage ("User name already exits") }Else{Keychainitem.setobject ( Self. passwordTextField.text.dataUsingEncoding (nsutf8stringencoding,allowlossyconversion:true)!,Forkey:Ksecvaluedata asString) var status =Secitemadd(Keychainitem,Nil) Self. Alertwithstatus (Status)}}
Update Keychain
The Secitemupdate function is used to update keychain, two parameters, the first parameter is a description dictionary, and the second is a dictionary that contains the updated data
@IBAction func Updatekeychainitem (sender:anyobject) {varKeychainitem = Self. Createdefaultkeychainitemdic ()ifSecitemcopymatching (keychainitem,nil) = = noerr{varUpdatedictionary = Nsmutabledictionary () updatedictionary.setobject ( Self. passwordTextField.text.dataUsingEncoding (nsutf8stringencoding, Allowlossyconversion:true)!, Forkey:ksecvaluedata asString)varStatus = Secitemupdate (keychainitem,updatedictionary) Self. Alertwithstatus (Status)}Else{ Self. Alertwithmessage ("The keychain doesnot exist") } }
Delete Keychain
The Secitemdelete function is used to delete
@IBAction func deleteKeyChainItem(sender:AnyObject) { self.createDefaultKeyChainItemDic() ifSecItemCopyMatching(keyChainItem,nil) == noErr{ SecItemDelete(keyChainItem) self.alertWithStatus(status) }else{ self.alertWithMessage("The keychain doesnot exist") } }
Get Keychain
Secitemcopymatching The second parameter contains the dictionary information obtained. The conversion method is a bit complicated.
@IBAction func Getkeychainitem (sender:anyobject) {varKeychainitem= Self.Createdefaultkeychainitemdic () Keychainitem.SetObject (Kcfbooleantrue, Forkey:ksecreturndata asString) Keychainitem.SetObject (Kcfbooleantrue, forkey:ksecreturnattributes asString)varQueryresult:unmanaged<Anyobject? LetStatus=Secitemcopymatching (Keychainitem,&QueryResult) LetOpaque=QueryResult?.Toopaque ()varContentsofkeychain:nsstring? if LetOp=opaque { LetRetrieveddata=Unmanaged<Nsdictionary>.Fromopaque (OP).Takeunretainedvalue () LetPassworddata=Retrieveddata.Objectforkey (Ksecvaluedata) as!NSData LetPasswordstring=NSString (Data: Passworddata, Encoding:nsutf8stringencoding)! Self.Alertwithmessage ("Password: \ (passwordstring)") }Else{ Self.Alertwithmessage ("The keychain doesnot exist") } }
Summarize
In a nutshell, there are four functions.
- Secitemcopymatching-Query and get
- Secitemupdate-Update
- Secitemadd-Add
- Secitemdelete-Delete
Welcome to my iOS detailed column, where I'll explain most of the most common iOS technologies
Http://blog.csdn.net/column/details/huangwenchen-ios-sdk.html
My blog iOS parts directory
http://blog.csdn.net/hello_hwc/article/details/45365385
IOS Data Persistence keychain (Swift Demo)