有时,当我在 Xcode 的设备上运行应用程序时,我会尝试访问密钥链,但由于错误而失败。这与任何已记录的密钥链错误代码都不匹配,无法一致地重现。(大约30% 的情况下会发生,我不清楚为什么会发生)。完全缺乏文档使得调试这个问题非常困难。知道是什么导致了这一切,以及如何解决吗?我使用 Xcode 5并在设备上运行 iOS 7.0.4。
There is an open issue about this here: https://github.com/soffes/sskeychain/issues/52
编辑: 为每个请求添加密钥链访问代码
我使用 SSKeychain
库来与 keychain 接口。
#define SERVICE @"default"
@implementation SSKeychain (EXT)
+ (void)setValue:(NSString *)value forKey:(NSString *)key {
NSError *error = nil;
BOOL success = NO;
if (value) {
success = [self setPassword:value forService:SERVICE account:key error:&error];
} else {
success = [self deletePasswordForService:SERVICE account:key error:&error];
}
NSAssert(success, @"Unable to set keychain value %@ for key %@ error %@", value, key, error);
if (!success) {
LogError(@"Unable to set value to keychain %@", error);
}
LogTrace(@"Will set keychain account %@. is to nil? %d", key, value == nil);
if (value == nil)
LogWarn(@"Setting keychain %@ to nil!!!", key);
}
+ (NSString *)valueForKey:(NSString *)key {
NSError *error = nil;
NSString *value = [self passwordForService:SERVICE account:key error:&error];
if (error && error.code != errSecItemNotFound) {
NSAssert(!error, @"Unable to retrieve keychain value for key %@ error %@", key, error);
LogError(@"Unable to retrieve keychain value for key %@ error %@", key, error);
}
return value;
}
+ (BOOL)removeAllValues {
LogInfo(@"Completely Reseting Keychain");
return [[self accountsForService:SERVICE] all:^BOOL(NSDictionary *accountInfo) {
return [self deletePasswordForService:SERVICE account:accountInfo[@"acct"]];
}];
}
@end
大多数情况下都没问题。有时我会遇到断言失败,无法写入或读取密钥链,从而导致关键断言失败。