Start a Project

How to store data in keychain

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.

Different ways to store data locally.

You can store data locally in the iOS applications in different ways. Some of them are mention below:

  1. UserDefaults
  2. Keychain
  3. Core Data

Implementing the Keychain API

Storing and retrieving data directly with Keychain is not easy. The Keychain API is difficult in use. It is written in  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).

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.

Below is an example that shows how to retrieve data from the keychain.

If you want to know more about this wrapper then follow the below link:

  1. https://cocoapods.org/pods/SwiftKeychainWrapper
  2. https://github.com/jrendel/SwiftKeychainWrapper

Thank you!!

Exit mobile version