import Foundation import Security struct LastFMKeychainStore: LastFMKeychainStoring { private let service = "com.hydraulophone.lastfm" private let account = "session" func load() throws -> LastFMStoredSession? { var query = baseQuery query[kSecReturnData as String] = true query[kSecMatchLimit as String] = kSecMatchLimitOne var result: CFTypeRef? let status = SecItemCopyMatching(query as CFDictionary, &result) if status == errSecItemNotFound { return nil } guard status == errSecSuccess, let data = result as? Data, let session = try? JSONDecoder().decode(LastFMStoredSession.self, from: data) else { throw LastFMError.keychainFailure } return session } func save(_ session: LastFMStoredSession) throws { let data: Data do { data = try JSONEncoder().encode(session) } catch { throw LastFMError.keychainFailure } let update = [kSecValueData as String: data] let updateStatus = SecItemUpdate(baseQuery as CFDictionary, update as CFDictionary) if updateStatus == errSecSuccess { return } guard updateStatus == errSecItemNotFound else { throw LastFMError.keychainFailure } var item = baseQuery item[kSecValueData as String] = data item[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly guard SecItemAdd(item as CFDictionary, nil) == errSecSuccess else { throw LastFMError.keychainFailure } } func delete() throws { let status = SecItemDelete(baseQuery as CFDictionary) guard status == errSecSuccess || status == errSecItemNotFound else { throw LastFMError.keychainFailure } } private var baseQuery: [String: Any] { [ kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: account, ] } }