1
votes

First time I am building iOS application, I got stuck in saving data securely. How to save sensitive data like username and password in keychain

in app I am using UserDefaults to store and retrieve like below

 UserDefaults.standard.set([unameTextfield.text], forKey: "userName")
 UserDefaults.standard.set([passwordTextfield.text], forKey: "userPassword")

for retrieving:

  let uName = UserDefaults.standard.string(forKey: "userName")
  let uPassword = UserDefaults.standard.string(forKey: "userPassword")

but I want to save data securely in Keychain, how to do that?

1

1 Answers

0
votes

You are correct, UserDefault is not a good solution when it comes to store sensitive information. Keychain is what you need; however, the problem is that keychain native API is not as easy/straighforward as Userdefault Api. So, I think a great solution is to use KeychainWrapper.

First, install it. Make your cocaopod file look like this

use_frameworks!
platform :ios, '8.0'

target 'target_name' do
   pod 'SwiftKeychainWrapper'
end

Then, install it from the terminal with pod install and import it. (This is from the docs)

import SwiftKeychainWrapper    

//Set value
let saveSuccessful: Bool = KeychainWrapper.standard.set("Some String", forKey: "myKey")

//get value
let retrievedString: String? = KeychainWrapper.standard.string(forKey: "myKey")