The Keychain is a secure storage mechanism provided by Apple to securely store sensitive information like passwords, tokens, and certificates. This information can be accessed by an authenticated user only and is stored in an encrypted format.
In this example, we will see how we can use the Keychain to store and retrieve a user’s access token:
main.swift16 chars2 lines
main.swift112 chars5 lines
The serviceName
is a unique identifier for the Keychain service you are going to use. The accessTokenKey
is the key under which the access token will be stored in the Keychain.
main.swift480 chars15 lines
The above code creates a dictionary containing the service name, access token key, and the access token data. Then it adds this information to the Keychain using the SecItemAdd
method. If there is an error, it throws a KeychainError.unhandledError
error.
main.swift680 chars21 lines
The above code creates a dictionary containing the service name, access token key, and some additional parameters to retrieve the data. Then it uses the SecItemCopyMatching
method to retrieve the data from the Keychain. If there is an error, it throws a KeychainError.unhandledError
error.
KeychainError.unhandledError
error can be defined as follows:main.swift70 chars4 lines
OSStatus is an integer type and represents the result of a Keychain operation.
That’s it! You can now securely store and retrieve sensitive information like access tokens using the Keychain in iOS.
gistlibby LogSnag