Update: This issue has been fixed in Xcode 8.2. Keychain works in the simulator without enabling keychain sharing.
Why am I always receiving error -34018 when calling SecItemAdd
function in Xcode 8 / iOS 10 simulator?
Create a new Single page iOS app project in Xcode 8.
Run the following code in viewDidLoad
(or open this Xcode project).
let itemKey = "My key"
let itemValue = "My secretive bee ๐"
// Remove from Keychain
// ----------------
let queryDelete: [String: AnyObject] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: itemKey as AnyObject
]
let resultCodeDelete = SecItemDelete(queryDelete as CFDictionary)
if resultCodeDelete != noErr {
print("Error deleting from Keychain: \(resultCodeDelete)")
}
// Add to keychain
// ----------------
guard let valueData = itemValue.data(using: String.Encoding.utf8) else {
print("๐ฃ๐ฃ๐ฃ๐ฃ๐ฃ๐ฃ๐ฃ๐ฃ๐ฃ๐ฃ Error saving text to Keychain")
return
}
let queryAdd: [String: AnyObject] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: itemKey as AnyObject,
kSecValueData as String: valueData as AnyObject,
kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlocked
]
let resultCode = SecItemAdd(queryAdd as CFDictionary, nil)
if resultCode != noErr {
print("๐๐๐๐๐๐๐๐๐ Error saving to Keychain: \(resultCode).")
} else {
print("๐๐๐๐๐๐๐๐๐ Saved to keychain successfully.")
}
Item is added to Keychain.
Function SecItemAdd returns the following error code: -34018
.
Xcode version 8.1 (8B62), macOS Sierra 10.12.1.
Always occurs in Xcode 8 since Beta 2 when testing in an iOS 10 simulator.
Does NOT occur in Xcode 8 when testing in an iOS 9.3 simulator.
https://dl.dropboxusercontent.com/u/11143285/2016/07/KeychainBugDemo.zip
Radar: https://openradar.appspot.com/27422249
Apple Developer Forums: https://forums.developer.apple.com/message/179846
This issue is different from the following post because it occurs consistently in Xcode 8. SecItemAdd and SecItemCopyMatching returns error code -34018 (errSecMissingEntitlement)
I was able to work around this in my app by adding Keychain Access Groups to the Entitlements file. I turned on the Keychain Sharing switch in the Capabilities section in your test app, and it is working for me as well.
Item to add to entitlements:
<key>keychain-access-groups</key>
<array>
<string>$(AppIdentifierPrefix)com.evgenii.KeychainBugDemo</string>
</array>
I have only tried this on macOS Sierra (10.12), so I'm not sure if it will work for you on 10.11.5.