iOS 中的钥匙串访问:"Keychain failed to store the value with code: -50"

Keychain access in iOS: "Keychain failed to store the value with code: -50"

我在调用 SecItemAdd 时没有找到有关此类错误代码的信息,可能是什么原因造成的?

提前致谢

编辑: 这是我收到错误的函数:

+ (BOOL)storeWithKey:(NSString *)keyStr withValueStr:(NSString *)valueStr
{
   if ((keyStr != nil) && (![keyStr isEqualToString:@""]) &&
       (valueStr != nil) && (![valueStr isEqualToString:@""])) {

       NSData *valueData = [valueStr dataUsingEncoding:NSUTF8StringEncoding];
       NSString *service = [[NSBundle mainBundle] bundleIdentifier];

       NSDictionary *secItem = @{(__bridge id)kSecClass : (__bridge id)kSecClassInternetPassword,
                              (__bridge id)kSecAttrService : service,
                              (__bridge id)kSecAttrAccount : keyStr,
                              (__bridge id)kSecValueData : valueData};

       CFTypeRef result = NULL;

       // Store value and get the result code
       OSStatus status = SecItemAdd((__bridge CFDictionaryRef)secItem, &result);

       NSLog(@"'writeToKeychain'. %@", [self getErrorMessage:status]);

       return [self checkIfInKeychain:status];
   }
   else {
       return NO;
   }
}

错误代码的文档在 Security/SecBase.h 文件中。你可以在最后找到它们。

您还可以在 SecItemAdd 的文档中找到它们。 https://developer.apple.com/library/ios/documentation/Security/Reference/keychainservices/#//apple_ref/doc/uid/TP30000898-CH5g-CJBEABHG

-50表示One or more parameters passed to a function were not valid。你是错误的参数组合。

如果您使用 kSecAttrServicekSecAttrAccountkSecClass 应该是 kSecClassGenericPassword

NSDictionary *secItem = @{(__bridge id)kSecClass : (__bridge id)kSecClassGenericPassword,
                          (__bridge id)kSecAttrService : service,
                          (__bridge id)kSecAttrAccount : keyStr,
                          (__bridge id)kSecValueData : valueData};

如果您将 kSecClassInternetPassword 用作 kSecClass,则应使用 kSecAttrServerkSecAttrPort(如果需要)而不是 kSecAttrService

NSDictionary *secItem = @{(__bridge id)kSecClass : (__bridge id)kSecClassInternetPassword,
                          (__bridge id)kSecAttrServer : @"example.com",
                          (__bridge id)kSecAttrPort : @(80), // Optional
                          (__bridge id)kSecAttrAccount : keyStr,
                          (__bridge id)kSecValueData : valueData};