CodableKeychain is a Swift framework for saving objects conforming to the Codable
protocol to the keychain.
- iOS 8.0+, macOS 10.10+, tvOS 9.0+, watchOS 2.0+
- 100% Test Coverage
- Easily store any object conforming to
Codable
- Specify item accessibility using a Swift enum (see
Keychain.AccessibleOption
) - Converts the 35 documented keychain error codes into a Swift enum for easy error handling (see
KeychainError
)
The KeychainStorable
protocol, which inherits from Codable
, is used to define a model that can be stored using CodableKeychain.
Note: If you do not define a service or access group, CodableKeychain will default to your app's bundle identifier for the service and
nil
for the access group.
import CodableKeychain
enum Constants {
static let service = "com.example.credentialservice"
static let accessGroup = "[APP_ID_PREFIX].com.example.TestKeychain"
}
struct Credential: KeychainStorable {
let email: String
let password: String
let pin: Int
let dob: Date
}
extension Credential {
var account: String { return email }
var accessible: Keychain.AccessibleOption { return .whenPasscodeSetThisDeviceOnly }
}
If the service and access group will be the same for all keychain operations, use the following to configure default values:
Keychain.configureDefaults(withService: Constants.service, accessGroup: Constants.accessGroup)
To reset the defaults:
Keychain.resetDefaults()
let credential = Credential(email: "[email protected]", password: "foobar", pin: 1234, dob: Date(timeIntervalSince1970: 100000))
do {
try Keychain.default.store(credential)
} catch let error {
print(error)
}
do {
let credential: Credential? = try Keychain.default.retrieveValue(forAccount: "[email protected]")
} catch let error {
print(error)
}
Note: CodableKeychain requires Swift 4 (and Xcode 9) or greater.
Targets using CodableKeychain must support embedded Swift frameworks.
CocoaPods is a centralized dependency manager for Cocoa projects. To install CodableKeychain with CocoaPods:
-
Make sure the latest version of CocoaPods is installed.
-
Add CodableKeychain to your Podfile:
use_frameworks!
pod 'CodableKeychain', '~> 1.0.0'
- Run
pod install
.
Swift Package Manager is Apple's official package manager for Swift frameworks. To install with Swift Package Manager:
- Add CodableKeychain to your Package.swift file:
import PackageDescription
let package = Package(
name: "MyAppTarget",
dependencies: [
.Package(url: "https://github.com/toddkramer/CodableKeychain", majorVersion: 1, minor: 0)
]
)
-
Run
swift build
. -
Generate Xcode project:
swift package generate-xcodeproj
Carthage is a decentralized dependency manager for Cocoa projects. To install CodableKeychain with Carthage:
-
Make sure Carthage is installed.
-
Add CodableKeychain to your Cartfile:
github "toddkramer/CodableKeychain" ~> 1.0.0
- Run
carthage update
and add the appropriate framework.