从 Keychain 检索数据时,一小部分用户会收到 errSecItemNotFound

Small percentage of users getting errSecItemNotFound when retrieving data from the Keychain

我有一个 iOS 应用程序,它在钥匙串中存储访问令牌。在过去的几个月里,我注意到大约 2% 的用户在尝试检索令牌时收到 errSecItemNotFound

所有相关的 Whosebug 线程都指出后台任务是罪魁祸首 (iOS KeyChain not retrieving values from background) or including invalid params in the query string (Keychain: Item reported as errSecItemNotFound, but receive errSecDuplicateItem on addition)。

我正在使用 kSecAttrAccessibleAfterFirstUnlock 所以后台任务应该能够很好地访问钥匙串。

此外,搜索查询如下所示:

NSMutableDictionary *query = [[NSMutableDictionary alloc] init];
[query setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
[query setObject:(__bridge id)kCFBooleanTrue forKey:(__bridge id)kSecReturnData];
[query setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit];
[query setObject:service forKey:(__bridge id)kSecAttrService];
[query setObject:key forKey:(__bridge id)kSecAttrGeneric];
[query setObject:key forKey:(__bridge id)kSecAttrAccount];

(设置kSecAttrGeneric可能是多余的,但无论如何都不影响查询结果)

郑重声明,我在 SSKeyChain and UICKeychainStore.

中都遇到过这个错误

任何提示将不胜感激:]

我在使用 KDJKeychainItemWrapper 时遇到了类似的问题。最后,我将其对 kSecAttrGeneric 的使用替换为使用 kSecAttrService。这解决了我所有因未定义服务而找不到条目和重复项的问题。

我相信 kSecClassGenericPassword 的主键只是 kSecAttrAccount 和 kSecAttrService。

如果您不使用 kSecAttrGeneric,它应该自行解决,也许用户必须重新输入密码。

还要选择一个不会与其他任何内容冲突的服务名称。