### Configure Swift Package Manager for KeychainAccess Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Example `Package.swift` file configuration for integrating KeychainAccess using Swift Package Manager. It specifies the package name, products, and dependencies, including the URL and version of the KeychainAccess library. ```swift // swift-tools-version:5.0 import PackageDescription let package = Package( name: "MyLibrary", products: [ .library(name: "MyLibrary", targets: ["MyLibrary"]) ], dependencies: [ .package(url: "https://github.com/kishikawakatsumi/KeychainAccess.git", from: "3.0.0") ], targets: [ .target(name: "MyLibrary", dependencies: ["KeychainAccess"]) ] ) ``` -------------------------------- ### Install KeychainAccess with CocoaPods Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Instructions for installing the KeychainAccess library using CocoaPods. This involves adding `use_frameworks!` and `pod 'KeychainAccess'` to the project's Podfile. ```ruby use_frameworks! pod 'KeychainAccess' ``` -------------------------------- ### Configure Keychain Service, Label, Sync, and Accessibility (Swift) Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Illustrates the fluent interface provided by KeychainAccess for configuring keychain items. This example sets the service name, label, enables synchronization, and defines the accessibility level. ```swift let keychain = Keychain(service: "com.example.github-token") .label("github.com (kishikawakatsumi)") .synchronizable(true) .accessibility(.afterFirstUnlock) ``` -------------------------------- ### Create Keychain Instances for Internet Passwords (Swift) Source: https://context7.com/kishikawakatsumi/keychainaccess/llms.txt Illustrates the creation of KeychainAccess instances specifically for storing server credentials and web passwords. Examples include setting up for HTTPS servers, specifying authentication types like HTML forms, and configuring with custom labels and comments. ```swift import KeychainAccess // Create keychain for HTTPS server let keychain = Keychain(server: "https://api.github.com", protocolType: .https) // Specify authentication type for web forms let keychain = Keychain( server: "https://example.com", protocolType: .https, authenticationType: .htmlForm ) // Internet password with access group let keychain = Keychain( server: "https://api.example.com", protocolType: .https, accessGroup: "ABCDE12345.shared" ) // Configure with custom label let keychain = Keychain(server: "https://github.com", protocolType: .https) .label("GitHub API") .comment("Personal access token") ``` -------------------------------- ### Initializing Keychain for Application Password Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Provides examples of how to instantiate the Keychain object for managing application-specific passwords. It can be initialized with a service name and optionally an access group for shared Keychain items. ```swift let keychain = Keychain(service: "com.example.github-token") ``` ```swift let keychain = Keychain(service: "com.example.github-token", accessGroup: "12ABCD3E4F.shared") ``` -------------------------------- ### List All Keys with KeychainAccess Source: https://context7.com/kishikawakatsumi/keychainaccess/llms.txt This code example demonstrates how to retrieve all keys stored within a KeychainAccess instance or across different item classes. It shows fetching keys for the current keychain, all generic password items, and all internet password items. ```swift import KeychainAccess let keychain = Keychain(service: "com.example.myapp") // Get all keys for this keychain let keys = keychain.allKeys() print("Found \(keys.count) keys:") for key in keys { print(" - \(key)") } // Get all keys for a specific item class across all services let allGenericKeys = Keychain.allKeys(.genericPassword) for (service, key) in allGenericKeys { print("Service: \(service), Key: \(key)") } let allInternetKeys = Keychain.allKeys(.internetPassword) for (server, key) in allInternetKeys { print("Server: \(server), Key: \(key)") } ``` -------------------------------- ### Retrieving String Items from KeychainAccess Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Demonstrates how to retrieve string values from the Keychain using subscripting and the `get` or `getString` methods. It also shows how to safely unwrap optional values. ```swift let token = keychain["kishikawakatsumi"] ``` ```swift let token = keychain[string: "kishikawakatsumi"] ``` ```swift let token = try? keychain.get("kishikawakatsumi") ``` ```swift let token = try? keychain.getString("kishikawakatsumi") ``` -------------------------------- ### Enable iCloud Keychain Synchronization (Swift) Source: https://context7.com/kishikawakatsumi/keychainaccess/llms.txt Demonstrates how to enable iCloud synchronization for keychain items, allowing them to be accessed across different devices linked to the same Apple ID. Includes setup and retrieval of synced items. ```swift import KeychainAccess let keychain = Keychain(service: "com.example.myapp") // Create instance with sync enabled let syncedKeychain = keychain.synchronizable(true) syncedKeychain["synced_token"] = "value_available_on_all_devices" // One-shot synchronizable set do { try keychain .synchronizable(true) .set("multi_device_token", key: "cloud_token") print("Token will sync via iCloud") } catch { print("Error: \(error)") } // Retrieve synced item (searches both local and iCloud) if let token = syncedKeychain["cloud_token"] { print("Synced token: \(token)") } ``` -------------------------------- ### Generate Strong Random Passwords with KeychainAccess Source: https://context7.com/kishikawakatsumi/keychainaccess/llms.txt This code example shows how to generate a strong, random password using KeychainAccess, suitable for Safari. It also demonstrates how to use the generated password to save a new account in the keychain. ```swift import KeychainAccess // Generate password in format: xxx-xxx-xxx-xxx let password = Keychain.generatePassword() print("Generated password: \(password)") // Example output: "Nhu-GKm-s3n-pMx" // Use generated password for new account let keychain = Keychain(server: "https://www.example.com", protocolType: .https) let username = "newuser@example.com" keychain[username] = password keychain.setSharedPassword(password, account: username) { error in if error == nil { print("Strong password saved") } } ``` -------------------------------- ### Obtain All Stored Keys in Swift Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Retrieves all keys stored in the keychain. It initializes a Keychain object with a server and protocol type, then calls the `allKeys()` method to get an array of keys, which are subsequently printed. ```swift let keychain = Keychain(server: "https://github.com", protocolType: .https) let keys = keychain.allKeys() for key in keys { print("key: \(key)") } ``` -------------------------------- ### Biometric Authentication with KeychainAccess (Swift) Source: https://context7.com/kishikawakatsumi/keychainaccess/llms.txt Demonstrates how to store and retrieve keychain items protected by biometric authentication (Touch ID/Face ID) using the KeychainAccess library. It includes examples for setting accessibility, authentication policies, and custom authentication prompts. Note that operations involving sensitive data should be performed on a background thread. ```swift import KeychainAccess let keychain = Keychain(service: "com.example.myapp") // Store biometric-protected item (must run in background thread) DispatchQueue.global().async { do { try keychain .accessibility(.whenPasscodeSetThisDeviceOnly, authenticationPolicy: [.biometryAny]) .set("super_secret_token", key: "protected_token") print("Biometric-protected item stored") } catch { print("Error storing protected item: \(error)") } } // Retrieve with custom authentication prompt (must run in background thread) DispatchQueue.global().async { do { let token = try keychain .authenticationPrompt("Authenticate to access your secure token") .get("protected_token") DispatchQueue.main.async { if let token = token { print("Authenticated! Token: \(token)") } } } catch { print("Authentication failed: \(error)") } } // Update protected item with authentication DispatchQueue.global().async { do { try keychain .accessibility(.whenPasscodeSetThisDeviceOnly, authenticationPolicy: [.biometryAny]) .authenticationPrompt("Authenticate to update your token") .set("new_token_value", key: "protected_token") } catch { print("Update failed: \(error)") } } ``` -------------------------------- ### Remove Keychain Items (Swift) Source: https://context7.com/kishikawakatsumi/keychainaccess/llms.txt Provides examples for removing specific items or clearing all data associated with a keychain service. Shows removal using nil assignment and explicit remove methods, with error handling. ```swift import KeychainAccess let keychain = Keychain(service: "com.example.myapp") // Remove using subscript (set to nil) keychain["old_token"] = nil // Remove with error handling do { try keychain.remove("api_token") print("Token removed successfully") } catch { print("Failed to remove token: \(error)") } // Remove all items from this keychain do { try keychain.removeAll() print("All items cleared") } catch { print("Failed to clear keychain: \(error)") } ``` -------------------------------- ### Retrieve String Values from Keychain (Swift) Source: https://context7.com/kishikawakatsumi/keychainaccess/llms.txt Explains how to retrieve stored string values from KeychainAccess using subscript notation or `get` methods. It covers retrieving optional values via subscripts, using explicit string subscripts, and performing retrieval with explicit error handling, including an alternative `getString` method. ```swift import KeychainAccess let keychain = Keychain(service: "com.example.myapp") // Retrieve using subscript (returns optional) if let token = keychain["api_token"] { print("Token: \(token)") } else { print("Token not found") } // Explicit string subscript let password = keychain[string: "password"] // Retrieve with error handling do { if let username = try keychain.get("username") { print("Username: \(username)") } else { print("No username stored") } } catch { print("Retrieval error: \(error)") } // Alternative get method do { let token = try keychain.getString("github_token") print("Token retrieved: \(token ?? "none")") } catch { print("Error: \(error)") } ``` -------------------------------- ### Shared Web Credentials: Get, Save, and Set Password Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Illustrates how to interact with Shared Web Credentials to manage user credentials between an iOS app and its website counterpart. It covers checking the app's keychain first, then attempting to read from Shared Web Credentials, and finally saving credentials to both locations upon successful login. ```swift let keychain = Keychain(server: "https://www.kishikawakatsumi.com", protocolType: .HTTPS) let username = "kishikawakatsumi@mac.com" // First, check the credential in the app's Keychain if let password = try? keychain.get(username) { // If found password in the Keychain, // then log into the server } else { // If not found password in the Keychain, // try to read from Shared Web Credentials keychain.getSharedPassword(username) { (password, error) -> () in if password != nil { // If found password in the Shared Web Credentials, // then log into the server // and save the password to the Keychain keychain[username] = password } else { // If not found password either in the Keychain also Shared Web Credentials, // prompt for username and password // Log into server // If the login is successful, // save the credentials to both the Keychain and the Shared Web Credentials. keychain[username] = inputPassword keychain.setSharedPassword(inputPassword, account: username) } } } ``` -------------------------------- ### Initializing Keychain for Internet Password Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Illustrates how to create a Keychain instance for storing internet passwords. This includes specifying the server URL, protocol type, and optionally the authentication type. ```swift let keychain = Keychain(server: "https://github.com", protocolType: .https) ``` ```swift let keychain = Keychain(server: "https://github.com", protocolType: .https, authenticationType: .htmlForm) ``` -------------------------------- ### Create Keychain Instances for Application Passwords (Swift) Source: https://context7.com/kishikawakatsumi/keychainaccess/llms.txt Demonstrates creating KeychainAccess instances for storing generic application passwords and tokens. It shows how to use the app bundle identifier as the service name, specify a custom service name, create a keychain with an access group for inter-app sharing, and configure accessibility and iCloud synchronization. ```swift import KeychainAccess // Use app bundle identifier as service name let keychain = Keychain() // Specify custom service name let keychain = Keychain(service: "com.example.myapp") // Create keychain with access group for sharing between apps let keychain = Keychain(service: "com.example.myapp", accessGroup: "ABCDE12345.shared") // Configure with accessibility and iCloud sync let keychain = Keychain(service: "com.example.myapp") .accessibility(.afterFirstUnlock) .synchronizable(true) .label("GitHub Token") .comment("OAuth token for API access") ``` -------------------------------- ### Default Keychain Accessibility (Swift) Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Demonstrates creating a Keychain instance with the default accessibility setting, which matches background applications (`.afterFirstUnlock`). ```swift let keychain = Keychain(service: "com.example.github-token") ``` -------------------------------- ### Setting Label and Comment for Keychain Items Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Demonstrates how to associate a label and comment with a Keychain item for better identification and management. This is done using chained method calls before setting the item. ```swift let keychain = Keychain(server: "https://github.com", protocolType: .https) do { try keychain .label("github.com (kishikawakatsumi)") .comment("github access token") .set("01234567-89ab-cdef-0123-456789abcdef", key: "kishikawakatsumi") } catch let error { print("error: (error)") } ``` -------------------------------- ### Swift: Debugging and Printing Keychain Contents Source: https://context7.com/kishikawakatsumi/keychainaccess/llms.txt This snippet demonstrates how to print all stored items in a KeychainAccess instance for debugging purposes. It shows how to inspect items programmatically by iterating through them and accessing their properties like server, key, and protocol. This is useful for understanding what data is stored and verifying its contents. ```swift import KeychainAccess let keychain = Keychain(server: "https://github.com", protocolType: .https) // Print keychain object to see all items print("\(keychain)") // Output: // [ // [authenticationType: default, key: user1, server: github.com, class: internetPassword, protocol: https] // [authenticationType: default, key: user2, server: github.com, class: internetPassword, protocol: https] // ] // Inspect items programmatically let items = keychain.allItems() for item in items { print("Server: \(item["server"] ?? "unknown")") print("Key: \(item["key"] ?? "unknown")") print("Protocol: \(item["protocol"] ?? "unknown")") print("Authentication: \(item["authenticationType"] ?? "default")") print("---") } ``` -------------------------------- ### Retrieve Binary Data from Keychain (Swift) Source: https://context7.com/kishikawakatsumi/keychainaccess/llms.txt Demonstrates how to retrieve binary data, such as Data objects, from the keychain using both subscripting and dedicated methods. Includes error handling for retrieval operations. ```swift import KeychainAccess import Foundation let keychain = Keychain(service: "com.example.myapp") // Retrieve Data using subscript if let encryptionKey = keychain[data: "encryption_key"] { print("Key size: \(encryptionKey.count) bytes") // Use the data: encryptionKey } // Retrieve with error handling do { if let certificateData = try keychain.getData("certificate") { print("Certificate retrieved: \(certificateData.count) bytes") // Process certificate data } else { print("Certificate not found") } } catch { print("Error retrieving certificate: \(error)") } ``` -------------------------------- ### List All Items with KeychainAccess Source: https://context7.com/kishikawakatsumi/keychainaccess/llms.txt This snippet shows how to retrieve all keychain items, including their attributes and values, using KeychainAccess. It covers fetching all items for the current keychain instance and all items of a specific class, like generic passwords. ```swift import KeychainAccess let keychain = Keychain(service: "com.example.myapp") // Get all items for this keychain let items = keychain.allItems() print("Stored items:") for item in items { if let key = item["key"] as? String, let value = item["value"] { print("\(key): \(value)") } } // Get all items for a specific class let allItems = Keychain.allItems(.genericPassword) for item in allItems { print("Item: \(item)") if let service = item["service"] as? String, let key = item["key"] as? String, let value = item["value"] { print(" Service: \(service)") print(" Key: \(key)") print(" Value: \(value)") } } ``` -------------------------------- ### Obtain All Stored Items in Swift Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Fetches all items stored within the keychain. After creating a Keychain instance, it uses the `allItems()` method to retrieve all stored items and prints each one. ```swift let keychain = Keychain(server: "https://github.com", protocolType: .https) let items = keychain.allItems() for item in items { print("item: \(item)") } ``` -------------------------------- ### Adding String Items to KeychainAccess Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Demonstrates adding string data to the Keychain using subscripting and the `set` method. The subscripting method provides a concise way to add string values. ```swift keychain["kishikawakatsumi"] = "01234567-89ab-cdef-0123-456789abcdef" ``` ```swift keychain[string: "kishikawakatsumi"] = "01234567-89ab-cdef-0123-456789abcdef" ``` ```swift keychain.set("01234567-89ab-cdef-0123-456789abcdef", key: "kishikawakatsumi") ``` -------------------------------- ### Error Handling when Setting Keychain Items Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Illustrates how to handle potential errors when saving items to the Keychain using a `do-catch` block. This ensures robust error management for Keychain operations. ```swift do { try keychain.set("01234567-89ab-cdef-0123-456789abcdef", key: "kishikawakatsumi") } catch let error { print(error) } ``` -------------------------------- ### Store Binary Data in Keychain (Swift) Source: https://context7.com/kishikawakatsumi/keychainaccess/llms.txt Details how to store binary data, such as encryption keys, certificates, or file contents, using KeychainAccess. It demonstrates storing `Data` objects via subscripts and the `set` method, including error handling and loading data from files. ```swift import KeychainAccess import Foundation let keychain = Keychain(service: "com.example.myapp") // Store Data using subscript let encryptionKey = Data([0x01, 0x02, 0x03, 0x04]) keychain[data: "encryption_key"] = encryptionKey // Store file contents if let imageData = try? Data(contentsOf: URL(fileURLWithPath: "/path/to/secret.bin")) { keychain[data: "certificate"] = imageData } // Store with error handling let secretData = "Secret Message".data(using: .utf8)! do { try keychain.set(secretData, key: "encrypted_message") print("Binary data stored") } catch { print("Failed to store data: \(error)") } ``` -------------------------------- ### Retrieve All Keychain Attributes (Swift) Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Demonstrates how to retrieve all attributes associated with a keychain item using its key. It uses a do-catch block for error handling and prints specific attributes like comment, label, and creator. ```swift let keychain = Keychain() do { let attributes = try keychain.get("kishikawakatsumi") { $0 } print(attributes?.comment) print(attributes?.label) print(attributes?.creator) ... } catch let error { print("error: \(error)") } ``` -------------------------------- ### Debug: Display All Stored Keychain Items Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Shows how to print all items stored in the keychain for debugging purposes. This method provides a string representation of the keychain's contents, listing each item with its attributes. ```swift let keychain = Keychain(server: "https://github.com", protocolType: .https) print("\(keychain)") ``` -------------------------------- ### One-Shot Set for Foreground Accessibility (Swift) Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Demonstrates a one-shot method to set a keychain item with `.whenUnlocked` accessibility. This is useful for foreground operations and includes error handling. ```swift let keychain = Keychain(service: "com.example.github-token") do { try keychain .accessibility(.whenUnlocked) .set("01234567-89ab-cdef-0123-456789abcdef", key: "kishikawakatsumi") } catch let error { print("error: \(error)") } ``` -------------------------------- ### Configure Keychain Accessibility Levels (Swift) Source: https://context7.com/kishikawakatsumi/keychainaccess/llms.txt Shows how to set different accessibility levels for keychain items, controlling when they can be accessed based on device state (e.g., unlocked, passcode set). ```swift import KeychainAccess let keychain = Keychain(service: "com.example.myapp") // Background app: accessible after first unlock do { try keychain .accessibility(.afterFirstUnlock) .set("background_token", key: "api_token") } catch { print("Error: \(error)") } // Foreground app: only when device unlocked do { try keychain .accessibility(.whenUnlocked) .set("foreground_secret", key: "sensitive_data") } catch { print("Error: \(error)") } // Device-only (won't backup to iCloud/iTunes) do { try keychain .accessibility(.whenUnlockedThisDeviceOnly) .set("device_specific", key: "local_key") } catch { print("Error: \(error)") } // Require passcode to be set if #available(iOS 8.0, *) { do { try keychain .accessibility(.whenPasscodeSetThisDeviceOnly) .set("highly_sensitive", key: "secure_data") } catch { print("Error: \(error)") } } ``` -------------------------------- ### Store String Values in Keychain (Swift) Source: https://context7.com/kishikawakatsumi/keychainaccess/llms.txt Provides methods for storing string values in the KeychainAccess library using subscript notation or the `set` method. It covers both silent error ignoring via subscripts and explicit error handling using `do-catch` blocks, including options for custom configurations. ```swift import KeychainAccess let keychain = Keychain(service: "com.example.myapp") // Store using subscript (errors are silently ignored) keychain["username"] = "john.doe@example.com" keychain["api_token"] = "ghp_1234567890abcdefghij" // Explicit string subscript keychain[string: "password"] = "SecureP@ssw0rd" // Store with error handling using set method do { try keychain.set("ghp_abcdefghij1234567890", key: "github_token") print("Token stored successfully") } catch let error { print("Failed to store token: \(error)") } // Store with custom configuration do { try keychain .accessibility(.whenUnlocked) .synchronizable(false) .set("sensitive_data", key: "secret_key") } catch { print("Storage error: \(error)") } ``` -------------------------------- ### Request Shared Web Credentials with KeychainAccess Source: https://context7.com/kishikawakatsumi/keychainaccess/llms.txt This snippet demonstrates how to request all shared web credentials for associated domains or for a specific domain using KeychainAccess. It handles potential errors and iterates through the retrieved credentials. ```swift import KeychainAccess // Request all credentials for associated domains Keychain.requestSharedWebCredential { credentials, error in if let error = error { print("Error: \(error)") return } for credential in credentials { if let server = credential["server"], let account = credential["account"], let password = credential["password"] { print("Found credential for \(account) on \(server)") // Use credentials to log in } } } // Request credentials for specific domain Keychain.requestSharedWebCredential(domain: "www.example.com") { credentials, error in guard error == nil else { print("Error: \(error!)") return } print("Found \(credentials.count) credentials for example.com") } ``` -------------------------------- ### One-Shot Set for Background Accessibility (Swift) Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Provides a one-shot method to set a keychain item with `.afterFirstUnlock` accessibility. This is useful for immediate operations, using a do-catch block for error handling. ```swift let keychain = Keychain(service: "com.example.github-token") do { try keychain .accessibility(.afterFirstUnlock) .set("01234567-89ab-cdef-0123-456789abcdef", key: "kishikawakatsumi") } catch let error { print("error: \(error)") } ``` -------------------------------- ### Share Keychain Items Between Apps (Swift) Source: https://context7.com/kishikawakatsumi/keychainaccess/llms.txt Explains and shows how to share keychain data between different applications using access groups. This requires proper entitlement configuration in Xcode. ```swift import KeychainAccess // App 1: Store shared data let sharedKeychain = Keychain( service: "com.example.shared", accessGroup: "ABCDE12345.com.example.shared" ) do { try sharedKeychain.set("shared_secret", key: "team_token") print("Shared data stored") } catch { print("Error: \(error)") } // App 2: Access shared data let appKeychain = Keychain( service: "com.example.shared", accessGroup: "ABCDE12345.com.example.shared" ) if let sharedToken = appKeychain["team_token"] { print("Retrieved shared token: \(sharedToken)") } ``` -------------------------------- ### One-Shot Set with iCloud Synchronization (Swift) Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Provides a one-shot method to set a keychain item with iCloud synchronization enabled. This is useful for immediate sync operations and includes error handling. ```swift let keychain = Keychain(service: "com.example.github-token") do { try keychain .synchronizable(true) .set("01234567-89ab-cdef-0123-456789abcdef", key: "kishikawakatsumi") } catch let error { print("error: \(error)") } ``` -------------------------------- ### Check Keychain Item Existence (Swift) Source: https://context7.com/kishikawakatsumi/keychainaccess/llms.txt Illustrates how to check if a specific key exists in the keychain without retrieving its value. Demonstrates checking with and without triggering the authentication UI. ```swift import KeychainAccess let keychain = Keychain(service: "com.example.myapp") // Check existence (may trigger authentication UI for protected items) do { if try keychain.contains("api_token") { print("Token exists") } else { print("Token not found") } } catch { print("Error checking existence: \(error)") } // Check without triggering authentication UI do { let exists = try keychain.contains("biometric_protected_key", withoutAuthenticationUI: true) if exists { print("Protected key exists (authentication not performed)") } } catch { print("Error: \(error)") } ``` -------------------------------- ### Retrieving NSData Items from KeychainAccess Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Shows how to retrieve binary data (`NSData`) from the Keychain using the subscripting syntax with the `data` key. This method is used for fetching non-textual data. ```swift let secretData = keychain[data: "secret"] ``` ```swift let data = try? keychain.getData("kishikawakatsumi") ``` -------------------------------- ### Enable iCloud Synchronization for Keychain Items (Swift) Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Demonstrates enabling iCloud synchronization for keychain items by setting the `synchronizable` property to `true`. This allows keychain items to be synced across a user's devices via iCloud. ```swift let keychain = Keychain(service: "com.example.github-token") .synchronizable(true) keychain["kishikawakatsumi"] = "01234567-89ab-cdef-0123-456789abcdef" ``` -------------------------------- ### Obtaining Creation Date of Keychain Item Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Demonstrates how to fetch the creation date of a Keychain item. This attribute can be useful for auditing or managing item lifecycles, accessed via the attributes subscript. ```swift let keychain = Keychain() let creationDate = keychain[attributes: "kishikawakatsumi"]?.creationDate ... ``` -------------------------------- ### Shared Web Credentials: Request All Associated Domain Credentials Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Provides a method to request all credentials associated with the app's domain from Shared Web Credentials. This is useful for fetching multiple credentials at once. ```swift Keychain.requestSharedWebCredential { (credentials, error) -> () in } ``` -------------------------------- ### Set Keychain Item for Background Accessibility (Swift) Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Shows how to set a keychain item with `.afterFirstUnlock` accessibility. This is suitable for background operations where the item should be accessible after the device is unlocked for the first time. ```swift let keychain = Keychain(service: "com.example.github-token") .accessibility(.afterFirstUnlock) keychain["kishikawakatsumi"] = "01234567-89ab-cdef-0123-456789abcdef" ``` -------------------------------- ### Generate Strong Random Password Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Demonstrates how to generate a strong, random password using the Keychain library. The generated password follows the format used by Safari's autofill feature (e.g., xxx-xxx-xxx-xxx). ```swift let password = Keychain.generatePassword() // => Nhu-GKm-s3n-pMx ``` -------------------------------- ### Access Keychain Items Using Subscripting (Swift) Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Shows how to access keychain item attributes using Swift's subscripting syntax. This provides a more concise way to retrieve attributes if the key is known. ```swift let keychain = Keychain() if let attributes = keychain[attributes: "kishikawakatsumi"] { print(attributes.comment) print(attributes.label) print(attributes.creator) } ``` -------------------------------- ### Swift: Error Handling for Keychain Operations Source: https://context7.com/kishikawakatsumi/keychainaccess/llms.txt This snippet illustrates comprehensive error handling for KeychainAccess operations in Swift. It shows how to catch specific `NSError` codes for common keychain failures like item not found, user cancellation, and authentication errors. It also demonstrates graceful degradation for missing items and checks for biometric authentication availability before storing sensitive data. ```swift import KeychainAccess let keychain = Keychain(service: "com.example.myapp") // Handle specific errors do { try keychain.set("value", key: "test_key") print("Success") } catch let error as NSError { switch error.code { case -25300: // errSecItemNotFound print("Item not found") case -25291: // errSecUserCanceled print("User canceled authentication") case -25293: // errSecAuthFailed print("Authentication failed") case -128: // User canceled Touch ID print("Biometric authentication canceled") default: print("Keychain error [\(error.code)]: \(error.localizedDescription)") } } // Graceful degradation for missing items if let value = try? keychain.get("optional_key") { print("Found: \(value)") } else { print("Key doesn't exist or error occurred") } // Check for authentication availability before storing protected items DispatchQueue.global().async { do { try keychain .accessibility(.whenPasscodeSetThisDeviceOnly, authenticationPolicy: [.biometryAny]) .set("protected", key: "biometric_key") } catch { print("Biometric storage failed (device may not support Touch ID/Face ID): \(error)") // Fall back to non-protected storage try? keychain.set("protected", key: "biometric_key") } } ``` -------------------------------- ### Adding NSData Items to KeychainAccess Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Shows how to store binary data (`NSData`) in the Keychain using the subscripting syntax with the `data` key. This is useful for storing non-textual information. ```swift keychain[data: "secret"] = NSData(contentsOfFile: "secret.bin") ``` -------------------------------- ### Advanced Biometric Policies for KeychainAccess (Swift) Source: https://context7.com/kishikawakatsumi/keychainaccess/llms.txt Illustrates advanced biometric and device passcode authentication policies for keychain items using KeychainAccess. It covers requiring the current biometric set, device passcode, and combining multiple authentication methods. These policies are subject to availability based on iOS versions. ```swift import KeychainAccess let keychain = Keychain(service: "com.example.myapp") // Require current biometric set (invalidated if fingerprints/Face ID changes) if #available(iOS 11.3, *) { DispatchQueue.global().async { do { try keychain .accessibility(.whenPasscodeSetThisDeviceOnly, authenticationPolicy: [.biometryCurrentSet]) .set("high_security_token", key: "secure_token") } catch { print("Error: \(error)") } } } // Require device passcode if #available(iOS 9.0, *) { DispatchQueue.global().async { do { try keychain .accessibility(.whenPasscodeSetThisDeviceOnly, authenticationPolicy: [.devicePasscode]) .set("passcode_protected", key: "pin_data") } catch { print("Error: \(error)") } } } // Multiple authentication options (biometry OR passcode) if #available(iOS 9.0, *) { DispatchQueue.global().async { do { try keychain .accessibility(.whenPasscodeSetThisDeviceOnly, authenticationPolicy: [.biometryAny, .or, .devicePasscode]) .set("flexible_auth_token", key: "token") } catch { print("Error: \(error)") } } } ``` -------------------------------- ### Saving Internet Password with KeychainAccess Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Shows how to save an internet password to the Keychain, typically used for website or server credentials. It requires specifying the server URL and protocol type. ```swift let keychain = Keychain(server: "https://github.com", protocolType: .https) keychain["kishikawakatsumi"] = "01234567-89ab-cdef-0123-456789abcdef" ``` -------------------------------- ### Shared Web Credentials with KeychainAccess (Swift) Source: https://context7.com/kishikawakatsumi/keychainaccess/llms.txt Shows how to use KeychainAccess to manage Shared Web Credentials, enabling credential sharing between an app and its corresponding website. It covers checking the app's keychain first, falling back to Shared Web Credentials, and saving new credentials to both locations. This feature is iOS-specific. ```swift import KeychainAccess // Check app keychain first, fall back to Shared Web Credentials let keychain = Keychain(server: "https://www.example.com", protocolType: .https) let username = "user@example.com" if let password = try? keychain.get(username) { // Found in app keychain, log in print("Logging in with stored password") } else { // Try Shared Web Credentials keychain.getSharedPassword(username) { password, error in if let password = password { // Found in Safari/Shared credentials print("Using shared password: \(password)") // Save to app keychain for next time keychain[username] = password } else { // Prompt user for credentials print("No saved credentials found") } } } // Save new credentials to both keychain and Shared Web Credentials let newPassword = "user_entered_password" keychain[username] = newPassword keychain.setSharedPassword(newPassword, account: username) { error in if let error = error { print("Error saving to Shared Web Credentials: \(error)") } else { print("Credentials saved and will be available in Safari") } } ``` -------------------------------- ### Removing Items from KeychainAccess Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Illustrates methods for removing items from the Keychain, including using subscripting by setting the value to `nil` and using the `remove` method with error handling. ```swift keychain["kishikawakatsumi"] = nil ``` ```swift do { try keychain.remove("kishikawakatsumi") } catch let error { print("error: (error)") } ``` -------------------------------- ### Set Keychain Item for Foreground Accessibility (Swift) Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Illustrates setting a keychain item with `.whenUnlocked` accessibility. This is intended for foreground operations where the item is only accessible when the device is unlocked. ```swift let keychain = Keychain(service: "com.example.github-token") .accessibility(.whenUnlocked) keychain["kishikawakatsumi"] = "01234567-89ab-cdef-0123-456789abcdef" ``` -------------------------------- ### Saving Application Password with KeychainAccess Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Demonstrates how to save an application-specific password to the Keychain using the KeychainAccess library. This method is suitable for storing credentials unique to your application. ```swift let keychain = Keychain(service: "com.example.github-token") keychain["kishikawakatsumi"] = "01234567-89ab-cdef-0123-456789abcdef" ``` -------------------------------- ### Add Touch ID (Face ID) Protected Keychain Item (Swift) Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Demonstrates adding a keychain item protected by Touch ID or Face ID. It specifies accessibility (`.whenPasscodeSetThisDeviceOnly`) and an authentication policy (`.biometryAny`), ensuring the operation runs on a background thread. ```swift let keychain = Keychain(service: "com.example.github-token") DispatchQueue.global().async { do { // Should be the secret invalidated when passcode is removed? If not then use `.WhenUnlocked` try keychain .accessibility(.whenPasscodeSetThisDeviceOnly, authenticationPolicy: [.biometryAny]) .set("01234567-89ab-cdef-0123-456789abcdef", key: "kishikawakatsumi") } catch let error { // Error handling if needed... } } ``` -------------------------------- ### Obtain Touch ID (Face ID) Protected Item with Custom Prompt Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Demonstrates how to retrieve a keychain item that is protected by Touch ID or Face ID. It shows how to specify a custom authentication prompt message. If the item is not protected, the prompt is ignored. This code runs asynchronously on a global dispatch queue. ```swift let keychain = Keychain(service: "com.example.github-token") DispatchQueue.global().async { do { let password = try keychain .authenticationPrompt("Authenticate to login to server") .get("kishikawakatsumi") print("password: (password)") } catch let error { // Error handling if needed... } } ``` -------------------------------- ### Retrieve Keychain Item Attributes with KeychainAccess Source: https://context7.com/kishikawakatsumi/keychainaccess/llms.txt This snippet illustrates how to access metadata and attributes of keychain items using KeychainAccess. It shows retrieving all attributes via a subscript and specific attributes using a handler, including persistent references. ```swift import KeychainAccess let keychain = Keychain(service: "com.example.myapp") // Get all attributes using subscript if let attributes = keychain[attributes: "api_token"] { print("Creation date: \(attributes.creationDate ?? Date())") print("Modification date: \(attributes.modificationDate ?? Date())") print("Label: \(attributes.label ?? \"none\")") print("Comment: \(attributes.comment ?? \"none\")") print("Accessible: \(attributes.accessible ?? \"unknown\")") print("Synchronizable: \(attributes.synchronizable ?? false)") print("Service: \(attributes.service ?? \"none\")") print("Account: \(attributes.account ?? \"none\")") } // Get attributes with handler do { let result = try keychain.get("api_token") { attributes -> String? in guard let attrs = attributes else { return nil } print("Item created: \(attrs.creationDate ?? Date())") print("Access group: \(attrs.accessGroup ?? \"none\")") // Return the actual value as string if let data = attrs.data { return String(data: data, encoding: .utf8) } return nil } print("Value: \(result ?? \"none\")") } catch { print("Error: \(error)") } // Get persistent reference for use with Keychain Services directly if let persistentRef = keychain[attributes: "api_token"]?.persistentRef { print("Persistent ref: \(persistentRef)") } ``` -------------------------------- ### Share Keychain Items Across Devices (Swift) Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Shows how to configure KeychainAccess to share keychain items across devices by specifying a service and an access group. This is essential for iCloud synchronization. ```swift let keychain = Keychain(service: "com.example.github-token", accessGroup: "12ABCD3E4F.shared") ``` -------------------------------- ### Obtaining Persistent Reference of Keychain Item Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Shows how to retrieve the persistent reference of a Keychain item, which can be used for uniquely identifying and accessing the item later. This is accessed via the attributes subscript. ```swift let keychain = Keychain() let persistentRef = keychain[attributes: "kishikawakatsumi"]?.persistentRef ... ``` -------------------------------- ### Update Touch ID (Face ID) Protected Keychain Item (Swift) Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Shows how to update a Touch ID or Face ID protected keychain item, including setting a custom authentication prompt message. This operation must also run on a background thread to avoid UI lock. ```swift let keychain = Keychain(service: "com.example.github-token") DispatchQueue.global().async { do { // Should be the secret invalidated when passcode is removed? If not then use `.WhenUnlocked` try keychain .accessibility(.whenPasscodeSetThisDeviceOnly, authenticationPolicy: [.biometryAny]) .authenticationPrompt("Authenticate to update your access token") .set("01234567-89ab-cdef-0123-456789abcdef", key: "kishikawakatsumi") } catch let error { // Error handling if needed... } } ``` -------------------------------- ### Remove Touch ID (Face ID) Protected Item Source: https://github.com/kishikawakatsumi/keychainaccess/blob/master/README.md Shows the process of removing a keychain item, including those protected by Touch ID or Face ID. It highlights that there is no specific prompt for authentication during removal. ```swift let keychain = Keychain(service: "com.example.github-token") do { try keychain.remove("kishikawakatsumi") } catch let error { // Error handling if needed... } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.