【问题标题】:Unable to retrieve data from SecItemCopyMatching无法从 SecItemCopyMatching 检索数据
【发布时间】:2014-05-26 12:03:36
【问题描述】:

我正在向钥匙串添加一个项目,然后我想获得该项目的价值。问题是,它原来是一个空字符串。我究竟做错了什么?谢谢!

//add item to keychain
NSDictionary *secItem = @{ (__bridge id)kSecClass : (__bridge id)kSecClassGenericPassword,
                           (__bridge id)kSecAttrService : [[NSBundle mainBundle] bundleIdentifier],
                           (__bridge id)kSecAttrAccount : myKeyVar,
                           (__bridge id)kSecValueData : [myValue dataUsingEncoding:NSUTF8StringEncoding],
                           (__bridge id)kSecAttrSynchronizable : @YES };

OSStatus status = SecItemAdd((__bridge CFDictionaryRef)secItem, NULL);
//successfully adds it

//query for existing item
NSDictionary *query = @{(__bridge id)kSecClass : (__bridge id)kSecClassGenericPassword,
                        (__bridge id)kSecAttrService : [[NSBundle mainBundle] bundleIdentifier],
                        (__bridge id)kSecAttrAccount : keyToSearchForVar,
                        (__bridge id)kSecAttrSynchronizable : @YES,
                        (__bridge id)kSecReturnAttributes : (__bridge id)kCFBooleanTrue};

CFDictionaryRef valueAttributes = NULL;
OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query,
                                      (CFTypeRef *)&valueAttributes);
NSDictionary *attributes = (__bridge_transfer NSDictionary *)valueAttributes;
//attributes has 8 key/value pairs but I don't see the stored encoded value as one of them

if (status == errSecSuccess) {
    NSString* myString = [[NSString alloc] initWithData:[attributes objectForKey:(__bridge id)kSecValueData] encoding:NSUTF8StringEncoding];
    //myString is @""
}

【问题讨论】:

  • 您对 kSecAttrAccount 参数 (myKeyVar/keyToSearchForVar) 使用不同的变量 - 它们是否包含相同的字符串?
  • 是的,它是同一个字符串。它们在不同的功能中,我传递了键和值,但确实确认它们是相同的。

标签: ios objective-c keychain


【解决方案1】:

问题是我定义了 kSecReturnAttributes 来要求它返回属性,但没有定义 kSecReturnData 来返回实际数据,这很重要。在查询中添加这一行解决了问题:

(__bridge id)kSecReturnData : (__bridge id)kCFBooleanTrue}

【讨论】:

    猜你喜欢
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多