SecItemAdd always returns error -34018 in Xcode 8 in iOS 10 simulator

Solution 1:

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.

Screenshot of turning on the switch

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.

Solution 2:

In Xcode 8.1 GM Release Notes Apple acknowledged the problem and suggested a cleaner workaround:

Keychain APIs may fail to work in the Simulator if your entitlements file doesn’t contain a value for the application-identifier entitlement. (28338972) Workaround: Add a user-defined build setting to your target named ENTITLEMENTS_REQUIRED and set the value to YES. This will cause Xcode to automatically insert an application-identifier entitlement when building.

Note that from what I have tried, it only works in Xcode 8.1. Although the text can mislead you into a build setting, what you need to do is add this to your Environment Variables, in your scheme.

enter image description here

Xcode 8.2 will solve this:

Resolved in Xcode 8.2 beta - IDE Keychain APIs work correctly in Simulator. (28338972)

Solution 3:

This can happen if you have a test target that does not have a host app. To fix

  1. add a dummy host app : enter image description here

  2. Enable automatic code signing and add a team :

enter image description here

  1. Enable keychain sharing in capabilities

enter image description here