A lightweight, thread-safe, and
Sendable Swift wrapper for Apple's Keychain Services on iOS, macOS, watchOS, and tvOS with built-in Codable serialization and automatic upserting.
- β‘ Swift Concurrency Ready: Conforms to
Sendablefor seamless usage across async tasks, actors, and background queues. - π Automatic Upsert: Smoothly updates existing keys without throwing
errSecDuplicateItemerrors. - π¦ Native Codable Support: Directly store and retrieve complex structs and data models (
store.setModel(user, forKey: "session")). - π‘οΈ Fine-Grained Accessibility: Easily specify item access policies (
.afterFirstUnlock,.whenUnlocked,.whenPasscodeSetThisDeviceOnly). - π₯ App Groups Compatible: Share credentials securely across apps, widgets, and app extensions using
accessGroup.
Add KeychainStore to your dependencies in Package.swift:
dependencies: [
.package(url: "https://github.com/nilkanthdesai76/swift-keychain-store.git", from: "1.0.0")
]import KeychainStore
// Standard store
let keychain = KeychainStore(service: "com.example.myapp")
// Shared App Group store (Widgets, App Extensions)
let sharedKeychain = KeychainStore(
service: "com.example.myapp",
accessGroup: "group.com.example.myapp"
)// Save or update
try keychain.setString("secure_access_token_xyz", forKey: "user_token")
// Read
if let token = try keychain.getString(forKey: "user_token") {
print("Found token: \(token)")
}
// Delete
try keychain.delete(forKey: "user_token")struct AuthSession: Codable {
let userId: String
let refreshToken: String
let expiresAt: Date
}
let session = AuthSession(userId: "usr_102", refreshToken: "ref_abc", expiresAt: Date())
// Persist struct directly
try keychain.setModel(session, forKey: "current_session")
// Retrieve struct directly
if let savedSession = try keychain.getModel(AuthSession.self, forKey: "current_session") {
print("Logged in as user: \(savedSession.userId)")
}Run tests via the Swift CLI:
swift testThis project is licensed under the MIT License - see the LICENSE file for details.