When working with Keychain in Swift, it is crucial to maintain a well-organized project structure. A recommended structure will help you manage your Keychain operations efficiently and improve code readability and maintainability.
Create a dedicated layer for accessing Keychain data. This could include functions for saving, retrieving, and deleting items from the Keychain.
Define constants for your Keychain service identifier. This helps avoid hardcoding strings throughout your code.
Implement error handling to manage possible Keychain operation failures gracefully.
import Foundation
import Security
class KeychainService {
private static let service = "com.example.myapp"
class func save(key: String, data: Data) -> OSStatus {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: key,
kSecValueData as String: data
]
SecItemDelete(query as CFDictionary) // Delete any existing item
return SecItemAdd(query as CFDictionary, nil)
}
class func load(key: String) -> Data? {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: key,
kSecReturnData as String: kCFBooleanTrue!,
kSecMatchLimit as String: kSecMatchLimitOne
]
var dataTypeRef: AnyObject? = nil
let status: OSStatus = SecItemCopyMatching(query as CFDictionary, &dataTypeRef)
guard status == errSecSuccess else { return nil }
return dataTypeRef as? Data
}
class func delete(key: String) -> OSStatus {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: key
]
return SecItemDelete(query as CFDictionary)
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?