A lightweight, pure-Swift library for the iOS keychain.
KeychainWrapper is a light weight swift wrapper for iOS keychain. Makes accessing keychain is exetremely simple as UserDefaults
. It is motivated by creating the app of boxueio.com.
The simplest use case is using the default
singleton. Then save and load data as the way of manipulating UserDefaults
.
Add values to keychain. All these set
methods return Bool
to indicate if the data was saved successfully. If the key already exists, the data will be overritten.
/// Save data
KeychainWrapper.default.set(1, forKey: "key.int.value")
KeychainWrapper.default.set([1, 2, 3], forKey: "key.array.value")
KeychainWrapper.default.set("string value", forKey: "key.string.value")
Retrieve values from keychain. All kinds of getter methods return T?
, if the data corresponding to forKey
cannot decoded back to T
, it returns nil
.
/// Load data
KeychainWrapper.default.object(of: Int.self, forKey: "key.int.value")
KeychainWrapper.default.object(of: Array.self, forKey: "key.array.value")
KeychainWrapper.default.string(forKey: "key.string.value")
Remove data from keychain. Return Bool
indicating if the delete was successful.
KeychainWrapper.default.removeObject(forKey: "key.to.be.deleted")
When you use the default
KeychainWrapper object, all keys are linked to your main bundle identifier as the service name. Howerver, you could change it as follows:
let serviceName = "Custom.Service.Name"
let myWrapper = KeychainWrapper(serviceName: serviceName)
You may also share keychain items by a customized access group:
let serviceName = "Custom.Service.Name"
let accessGroup = "Shared.Access.Group"
let myWrapper = KeychainWrapper(serviceName: serviceName, accessGroup: accessGroup)
The default
KeyChainWrapper object do not share any keychain item and its accessGroup
is nil
.
By default, all items saved by KeychainWrapper
can only be access when the device is unlocked. The enum KeychainItemAccessibility
gives you a customization point to specify another accessibility level.
KeychainWrapper.default.set(1, forKey: "key.int.value", withAccessibility: .afterFirstUnlock)
The
kSecAttrAccessibleAlways
andkSecAttrAccessibleAlwaysThisDeviceOnly
are deprecated by iOS 12.0. So we do not include them inKeychainItemAccessibility
.
To integrate KeychainWrapper into your Xcode project using Carthage, speicify the following line in your Cartfile
:
github "puretears/KeychainWrapper" ~> 1.0
We also recorded some videos talking about keychain basic and KeychainWrapper
implementation details (Chinese 🇨🇳, Subscription needed).
false
or nil
to indicate errors.KeychainWrapper is released under the MIT license. See LICENSE for details.