To store a string securely in the Keychain, you can use the Keychain Services API provided by Apple. Here's an example function that takes a string and a key name as input, and stores the string in the Keychain using the default kSecClassGenericPassword class:
main.swift497 chars19 lines
In this function, we first convert the input string into a Data
object using the UTF-8 encoding. Then we create a dictionary with the Keychain attributes that we want to set:
kSecClass
: The class of the Keychain item. In this case, we're using the kSecClassGenericPassword
class, which allows us to store arbitrary data as a password item.kSecAttrAccount
: The name of the Keychain item, which we set to the input key
.kSecValueData
: The data to be stored in the Keychain, which we set to the data
object.We also call SecItemDelete
to delete any existing Keychain item with the specified key, to avoid duplicates. Finally, we call SecItemAdd
to add the new item to the Keychain.
To read a string from the Keychain, you can use the SecItemCopyMatching
function with a similar query dictionary.
gistlibby LogSnag