Created
September 1, 2023 15:56
-
-
Save giovannamoeller/967dea90a43c63e15e76896c44156b89 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| // KeychainHelper.swift | |
| // VollMed | |
| // | |
| // Created by Giovanna Moeller on 28/08/23. | |
| // | |
| import Foundation | |
| import Security | |
| struct KeychainHelper { | |
| static func set(value: String, for key: String) -> Bool { | |
| if 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) | |
| let status = SecItemAdd(query as CFDictionary, nil) | |
| return status == errSecSuccess | |
| } | |
| return false | |
| } | |
| static func get(for key: String) -> String? { | |
| let query: [String: Any] = [ | |
| kSecClass as String: kSecClassGenericPassword, | |
| kSecAttrAccount as String: key, | |
| kSecReturnData as String: kCFBooleanTrue!, | |
| kSecMatchLimit as String: kSecMatchLimitOne | |
| ] | |
| var dataTypeRef: AnyObject? | |
| let status: OSStatus = SecItemCopyMatching(query as CFDictionary, &dataTypeRef) | |
| if status == errSecSuccess { | |
| if let data = dataTypeRef as? Data { | |
| return String(data: data, encoding: .utf8) | |
| } | |
| } | |
| return nil | |
| } | |
| static func delete(for key: String) -> Bool { | |
| let query: [String: Any] = [ | |
| kSecClass as String: kSecClassGenericPassword, | |
| kSecAttrAccount as String: key | |
| ] | |
| let status = SecItemDelete(query as CFDictionary) | |
| return status == errSecSuccess | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment