I am having trouble saving email and password to keychain. I have this based off of the documentation but it when I look at my keychain after I call the function I never see any new entries. Can anyone give me a good example or some guidance on saving credentials to the keychain so my users can login easier?
In my current implementation if I call the save function a second time I get this error Error: unhandledError(status: -25299) which is the errSecDuplicateItem code but when I look in the usernames and passwords list on my device I dont see those entries.
here is the button I am using to call the function to save those hardcoded values in keychain which is not working and the function for adding the secItem
Button(action: {
do {
try saveCredentialsToKeychain(username: "TESTUSERNAME",password:"TESTPASSWORD")
} catch {
// Handle the KeychainError or any other errors
print("Error: \(error)")
}
}) {
Text("Save")
.bold()
.frame(width: 150, height: 40)
.foregroundColor(.red)
.background(RoundedRectangle(cornerRadius: 10, style: .continuous)
.fill(.white))
}
func saveCredentialsToKeychain(username: String, password: String) throws {
let account = username
let password = password.data(using: String.Encoding.utf8)!
var query: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: account,
kSecValueData as String: password]
let status = SecItemAdd(query as CFDictionary, nil)
guard status == errSecSuccess else { throw KeychainError.unhandledError(status: status) }
}