A. Karnaval
A. Karnaval

Reputation: 797

How can I use keychain when I close my ios app?

I'm developing an iOS app and want user only type username:password pair only once (unless he logs out). Currently I use keychain-swift framework for storing emails/passwords.

I basically run:

let keychain = KeychainSwift()
keychain.set("johndoe", forKey: "my key") // on a successful login
keychain.get("my key")

When I run my app in a simulator I have to type password all the time (i.e., it doesn't look like it saves the password in keychain between the sessions).

Is it expected? What framework will allow me to save the data even when I close the app such that a user won't have to type username:password pairs every time to sign in?

Upvotes: 0

Views: 162

Answers (2)

CRD
CRD

Reputation: 53010

I have never used KeychainSwift but at a guess you could do something like:

let keychain = KeychainSwift(keyPrefix: "com.Daniel.myIOSapp.")
keychain.set("johndoe", forKey: "username")
keychain.set("where is jane", forKey: "password")

which will create two "generic password" keychain items com.Daniel.myIOSapp.username and com.Daniel.myIOSapp.password and the associated values.

You normally store the username/password pair as a single keychain item. You can do that with KeychainSwift using something like:

keychain.set("where is jane", forKey: "johndoe")

which creates a single generic password item in the keychain and you probably want to store "johndoe" in your preferences under a suitable key.

HTH

Upvotes: 1

Daniel
Daniel

Reputation: 9040

Haven't used this framework myself, but from looking at the code it appears that it will save, and therefore be accessible after app is restarted.

You might want to confirm the set function is working properly. From the readme here:

https://github.com/evgenyneu/keychain-swift/blob/master/README.md

...it states:

Check if operation was successful

One can verify if set, delete and clear methods finished successfully by checking their return values. Those methods return true on success and false on error.

if keychain.set("hello world", forKey: "my key") { // Keychain item is saved successfully } else { // Report error }

Also, just to confirm, the get function should read:

let myKey = keychain.get("my key")

...where myKey is put into your text field(s).

Upvotes: 0

Related Questions