1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| import UIKit import Security
class DPKeychain { static func saveToKeychain(_ value: String, service: String, account: String) -> Bool { guard let data = value.data(using: .utf8) else { return false } SecItemDelete(query(service: service, account: account) as CFDictionary) let query = [ kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: account, kSecValueData as String: data ] as [String: Any] let status = SecItemAdd(query as CFDictionary, nil) return status == errSecSuccess } static func loadFromKeychain(service: String, account: String) -> String? { let query = [ kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: account, kSecReturnData as String: kCFBooleanTrue!, kSecMatchLimit as String: kSecMatchLimitOne ] as [String: Any] var item: AnyObject? let status = SecItemCopyMatching(query as CFDictionary, &item) if status == errSecSuccess, let data = item as? Data { return String(data: data, encoding: .utf8) } return nil } static func deleteFromKeychain(service: String, account: String) -> Bool { let query = query(service: service, account: account) let status = SecItemDelete(query as CFDictionary) return status == errSecSuccess } private static func query(service: String, account: String) -> [String: Any] { return [ kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: account ] } }
|