无法从SecItemCopyMatching检索数据

时间:2014-04-12 07:47:10

标签: ios objective-c keychain

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

//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 @""
}

1 个答案:

答案 0 :(得分:2)

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

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