更新:此问题已在Xcode 8.2中修复。钥匙串可在模拟器中工作,而无需启用钥匙串共享。
为什么在Xcode 8 / iOS 10模拟器中调用函数时总是收到错误-34018 ?SecItemAdd
重现步骤
在Xcode 8中创建一个新的Single page iOS应用程序项目。在中运行以下代码viewDidLoad
(或打开此 Xcode项目)。
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.")
}
预期成绩
项目已添加到钥匙串。
实际结果
函数SecItemAdd返回以下错误代码:-34018
。
版
Xcode版本8.1(8B62),macOS Sierra 10.12.1。
组态
自从Beta 2在iOS 10模拟器中进行测试时,始终会在Xcode 8中发生。
在iOS 9.3模拟器中进行测试时,在Xcode 8中不会发生。
演示版
https://dl.dropboxusercontent.com/u/11143285/2016/07/KeychainBugDemo.zip
参考资料
雷达:https://openradar.appspot.com/27422249
苹果开发者论坛:https : //forums.developer.apple.com/message/179846
此问题与以下文章不同,因为它在Xcode 8中始终存在。SecItemAdd和SecItemCopyMatching返回错误代码-34018(errSecMissingEntitlement)