2011-08-19 95 views
15

我使用Apple的示例代码提供的KeyChainItemWrapper类将验证令牌保存到钥匙串中。使用KeyChainItemWrapper在KeyChain中存储密钥

KeychainItemWrapper *keychain = [[KeychainItemWrapper alloc] initWithIdentifier"JetTaxiApp_AuthToken" accessGroup:nil]; 

但是,当我试图将值设置为钥匙扣,奇数引发异常

[_authenticationTokenKeychain setObject:authenticationToken forKey: @"auth_token"]; 

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Couldn't add the Keychain Item.'

钥匙串尚不存在(在此调用的瞬间) 什么会导致此异常?

+1

确保您添加了钥匙串访问plist文件。 看看http://stackoverflow.com/questions/5859615/iphone-debugging-the-generickeychain-example – nessalabs

回答

33

您需要使用标准密钥,所以在这里您的@"auth_token"不正确。

The keys that can be used for this purpose and the possible values for each key are listed in the “Keychain Services Constants” section.

来源,有效常量的列表:Keychain Services Reference

例如,你可以使用:

[_authenticationTokenKeychain setObject:authenticationToken forKey: (__bridge NSString *)kSecValueData];

+12

当使用keychainItemWrapper的ARC版本时,你需要按照以下方法:'[_authenticationTokenKeychain setValue: authenticationToken forKey:(__ bridge NSString *)kSecValueData];' –

+1

@DamienMATHIEU我正在使用ARC版本,但我仍然有问题。我得到这个错误:'[ setValue:forUndefinedKey:]:这个类不是密钥值编码兼容的密钥v_Data'。任何想法可能是错的? – Interfector

+2

@Interfector而不是使用** setValue **,使用** setObject ** – fdezjose

0
[_authenticationTokenKeychain setObject:authenticationToken forKey: @"auth_token"]; 

对于上面的代码片段,关键参数是只能用钥匙由sdk提供。 您可以在SecItem.h中找到全部