Updated 28 January 2020
Keychain is secure storage. You can store all kinds of sensitive data in it: user passwords, credit card numbers, secret tokens, etc. Once stored in Keychain this information is only available to your app, other apps can’t see it. Besides that, the operating system makes sure this information is kept and processed securely.
Apple Inc. uses keychains as a password management system in Mac OS and iOS. Apple recommends storing only a small amount of data in the Keychain. If you need to secure something big you can encrypt it manually, save to a file and store the key in the Keychain.
Keychain data can accessible from jailbroken devices so try to avoid save data locally as much as possible.
You can store data locally in the iOS applications in different ways. Some of them are mention below:
Storing and retrieving data directly with Keychain is not easy. The Keychain API is difficult in use. It is written in C and requires a lot of time-consuming configuration. This page of Apple’s API reference documentation is also a great way to see how to implement Keychain directly in your app.
Apple and many other contributors have created wrappers to hide C code and organization powering things from beneath.
Apple’s own Keychain wrapper is called GenericKeychain and is available within the sample code in both Objective C and Swift. Other wrappers exist as Cocoapods or extension libraries on Github and other dependency management sites. We are going to implement KeyChain in our application using one of the available wrappers i.e (SwiftKeychainWrapper).
It provides a singleton instance that is set up to work for most needs. Use KeychainWrapper.standard
to access the singleton instance.
To use this you need to install it using podfile. Write pod 'SwiftKeychainWrapper'
in your pod file and to add this to your project.
To use this wrapper you need to import it in your project. For import write import SwiftKeychainWrapper
in your project file.
Below is an example of how to save data in keychain.
1 2 3 |
KeychainWrapper.standard.set(appleIDCredential.email!, forKey: Keys.email.rawValue) KeychainWrapper.standard.set(appleIDCredential.fullName?.givenName ?? "Test", forKey: Keys.fname.rawValue) KeychainWrapper.standard.set(appleIDCredential.fullName?.familyName ?? "Test", forKey: Keys.lname.rawValue) |
Below is an example that shows how to retrieve data from the keychain.
1 2 3 |
var firstName = KeychainWrapper.standard.string(forKey: Keys.fname.rawValue) var lastName = KeychainWrapper.standard.string(forKey: Keys.lname.rawValue) var email = KeychainWrapper.standard.string(forKey: Keys.email.rawValue) |
If you want to know more about this wrapper then follow the below link:
Thank you!!
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.