What is the Keychain and when do you use it?
Answer
The Keychain is iOS's secure, encrypted storage for sensitive data — passwords, authentication tokens, cryptographic keys. Unlike UserDefaults, data is encrypted and persists even after app deletion (unless configured otherwise). When to use Keychain: passwords, API tokens, OAuth tokens, private keys, biometric secrets — anything that must stay secure. Direct Keychain access (complex): import Security func saveToKeychain(key: String, value: String) { let data = value.data(using: .utf8)! let query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrAccount as String: key, kSecValueData as String: data ] SecItemDelete(query as CFDictionary) // Delete existing SecItemAdd(query as CFDictionary, nil) } func readFromKeychain(key: String) -> String? { let query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrAccount as String: key, kSecReturnData as String: true ] var result: AnyObject? SecItemCopyMatching(query as CFDictionary, &result) if let data = result as? Data { return String(data: data, encoding: .utf8) } return nil }. KeychainWrapper library (simpler): KeychainWrapper.standard.set(token, forKey: "authToken") let token = KeychainWrapper.standard.string(forKey: "authToken"). Sharing across apps (App Group Keychain): kSecAttrAccessGroup: "group.com.company.app". Access control: kSecAttrAccessible: kSecAttrAccessibleAfterFirstUnlock // Accessible after unlock kSecAttrAccessibleWhenUnlocked // Only when unlocked kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly // Requires passcode. Biometric protection: require Face ID/Touch ID to access: var accessControl = SecAccessControlCreateWithFlags(nil, kSecAttrAccessibleWhenUnlocked, .biometryCurrentSet, nil).
Previous
What is UserDefaults and when should you use it?
Next
What is dependency injection in Swift/iOS?