Save and Retrieve Data using KeyChain


In this article, we will learn how to save and retrieve data using Keychain in Swift.

We will start with an overview of the Keychain.

After that, we will learn how it works and why they are used.

So let’s begin with the article.

Overview of Keychain

We all save the small chunks of data which might be a password or any account information in our system, in iOS Apple provides the Keychain Services API to store the values in the Keychain in an encrypted form.

We can save any values like account information, bank details, and a short note in Keychain.

The Certificates and Provision profiles that we use for the app development are stored in the Keychain.

Check what Apple says about Keychain

How to save and retrieve data using Keychain

Let’s begin with the coding part. Here we will show how to save values and get values from the Keychain.

Here, we have declared a separate class named ManageKeyChain and inside it, we have declared the saveValues function that takes the values and saves the values to the Keychain using the Keychain Services API.

After that, a query object is used to save the values to the Keychain.

In addition, the query object contains the kSecClass, kSecAttrService, kSecAttrAccount, and kSecValueData keys.

kSecClass is the item’s class that defines the nature of the data and whether it should be encrypted or not.

kSecAttrService indicates the item’s service.

kSecAttrAccount indicates the account name.

kSecValueData is of type CFData and is the data that we are trying to save.

After that, we are using the function saveData() to save the data.

We will now call this function from our viewDidLoad()

Here is the output of the above.

Save and Retrieve Data using KeyChain

Try running the app again you will get the below output, as we are trying to save the same data.

Save and Retrieve Data using KeyChain

Similarly, we can retrieve the values saved by us. Here is the code to get the saved values.

Call this function from the viewDidLoad() as

Here is the result of calling this function.

Save and Retrieve Data using KeyChain

Above all, you can save any values and retrieve any saved values using Keychain.


Thanks for reading.

We hope you like the article about Keychain.

To read more articles please visit here.

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*

Be the first to comment.


All communication is done through a ticket system. I appreciate the regular almost daily updates of what is being worked on, and communicating changes or updates is easy through this system. Mobikul's response timeframe is quick.

Josh Arnold

Josh Arnold

Owner, Shop ATV Escape

Talk to Sales


Live Chat
Start a Project

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home