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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class ManageKeyChain { // function to save the values static func saveValues(service:String,account:String,password:Data) throws{ let query: [String: AnyObject] = [kSecClass as String:kSecClassGenericPassword, kSecAttrService as String: service as AnyObject, kSecAttrAccount as String:account as AnyObject, kSecValueData as String: password as AnyObject ] // saving data to Keychain let status = SecItemAdd(query as CFDictionary, nil) guard status != errSecDuplicateItem else{ print("Duplicate entry") return } // check the status if status == errSecSuccess { print("Save Successfull") } print("Saved") } } |
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()
1 2 3 4 5 6 7 |
func saveData(){ do{ try ManageKeyChain.saveValues(service: "google.com", account: "Mobikul", password: "password".data(using: .utf8)!) }catch{ print(error) } } |
Here is the output of the above.
Try running the app again you will get the below output, as we are trying to save the same data.
Similarly, we can retrieve the values saved by us. Here is the code to get the saved values.
1 2 3 4 5 6 7 8 9 |
static func getValues(service:String,account:String) -> Data{ // function to get the value let query: [String: AnyObject] = [kSecClass as String:kSecClassGenericPassword, kSecAttrService as String: service as AnyObject, kSecAttrAccount as String:account as AnyObject, kSecReturnData as String: kCFBooleanTrue, kSecMatchLimit as String: kSecMatchLimitOne ] var result : AnyObject? // copy something that matches our query let status = SecItemCopyMatching(query as CFDictionary, &result) return result as? Data ?? Data() print("read status", status) } |
Call this function from the viewDidLoad() as
1 2 3 4 5 |
func getData(){ let returnDat = ManageKeyChain.getValues(service: "google.com", account: "Mobikul") let pass = String(decoding: returnDat, as: UTF8.self) print("Password is ", pass) } |
Here is the result of calling this function.
Above all, you can save any values and retrieve any saved values using Keychain.
Conclusion
Thanks for reading.
We hope you like the article about Keychain.
To read more articles please visit here.