在 KeyChainItemWrapper 中保存密码时崩溃

2024-03-30

Apple 在他们的中提供了 KeyChainItemWrapper 类GenericKeyChain 示例代码 http://developer.apple.com/library/ios/#samplecode/GenericKeychain/Listings/Classes_KeychainItemWrapper_h.html。 SO 上有一个 ARC 解决方案,我正在尝试遵循:wrapper https://stackoverflow.com/a/16460308/92153存储在 iOS 上的 KeyChain 中。

包装器的用法是这样的:

KeychainItemWrapper *keychain = [[KeychainItemWrapper alloc] initWithIdentifier:@"F11-email-auth" accessGroup:nil];
[keychain setObject:[emailTextfield text] forKey:(__bridge id)(kSecMatchEmailAddressIfPresent)];
[keychain setObject:[passwordTextfield text] forKey:(__bridge id)(kSecClassGenericPassword)];

包含电子邮件文本字段的行被接受。 但是带有密码的第二行会崩溃,并出现以下异常。

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Couldn't add the Keychain Item.'
*** First throw call stack:
(
    0   CoreFoundation                      0x01b445e4 __exceptionPreprocess + 180
    1   libobjc.A.dylib                     0x018c78b6 objc_exception_throw + 44
    2   CoreFoundation                      0x01b44448 +[NSException raise:format:arguments:] + 136
    3   Foundation                          0x014a823e -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 116
    4   Feeltracker                         0x000053b3 -[KeychainItemWrapper writeToKeychain] + 899
    5   Feeltracker                         0x00004700 -[KeychainItemWrapper setObject:forKey:] + 272
    6   Feeltracker                         0x000092d6 -[FTLoginViewController connectToAccount:] + 374
    7   libobjc.A.dylib                     0x018d9874 -

可能是什么原因?我想知道这是否与我使用的常量有关。

UPDATE:

感谢 rmaddy 的帮助:

这似乎是引发错误的部分:

// No previous item found; add the new one.
result = SecItemAdd((__bridge CFDictionaryRef)[self dictionaryToSecItemFormat:keychainItemData], NULL);
NSAssert( result == noErr, @"Couldn't add the Keychain Item." );

结果为-50。 SecItemAdd 是一个 lib 方法。正如我所期望的,这在某种程度上与 KeyChain 处理直接相关......

keychainItemData contains: enter image description here


我无法再获得这个用于钥匙串包装器工作的 Apple 示例。 幸运的是,对此事的进一步研究揭示了这一点solution https://stackoverflow.com/questions/5247912/saving-email-password-to-keychain-in-ios,这对我有用。

请注意,该解决方案的原始答案不是 ARC 的,但是有人非常友善地创建了一个Github 上的 ARC 版本 https://github.com/jeremangnr/JNKeychain。我用过那个,效果非常好。

它是钥匙串的包装,工作原理比原来的更简单。

希望这可以帮助其他遇到类似问题的人。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 KeyChainItemWrapper 中保存密码时崩溃 的相关文章

随机推荐