Slightly updated Swift 5 version of add to/remove from keychain functionality:
@discardableResult
func addToKeychain(_ value: Data, tag: Data) -> Bool {
let attributes: [String: Any] = [
String(kSecClass): kSecClassKey,
String(kSecAttrApplicationTag): tag,
String(kSecValueData): value
]
var result: CFTypeRef? = nil
let status = SecItemAdd(attributes as CFDictionary, &result)
if status == errSecSuccess {
print("Successfully added to keychain.")
} else {
if let error: String = SecCopyErrorMessageString(status, nil) as String? {
print(error)
}
return false
}
return true
}
@discardableResult
func removeFromKeychain(_ value: Data, tag: Data) -> Bool {
let attributes: [String: Any] = [
String(kSecClass): kSecClassKey,
String(kSecAttrApplicationTag): tag,
String(kSecValueData): value
]
let status = SecItemDelete(attributes as CFDictionary)
if status == errSecSuccess {
print("Successfully removed from keychain.")
} else {
if let error: String = SecCopyErrorMessageString(status, nil) as String? {
print(error)
}
return false
}
return true
}
Which can be used like this:
let value: Data = "key".data(using: .utf8)!
let tag: Data = "com.test.key".data(using: .utf8)!
removeFromKeychain(value, tag: tag)
addToKeychain(value, tag: tag)