8.3. Finding Values in the Keychain
Problem
You want to query the keychain to find an existing item.
Solution
Use the SecItemCopyMatching
function. Follow these steps:
Construct a dictionary to pass to the aforementioned function. Add the
kSecClasskey to the dictionary. Set the key’s value to reflect the type of item that you are looking for. Usually the value should bekSecClassGenericPassword.Add the
kSecAttrServicekey to the dictionary. Set the key’s value to the service string of the item you are looking for. In this chapter, for service names, we use our app’s bundle identifier and we are setting the bundle identifiers of all our apps to the same string, so that one can write to the keychain, another can read the same data, etc.Add the
kSecAttrAccountkey to the dictionary and set its value to the actual key of the value that you previously stored in the keychain. If you followed the example that we wrote in Recipe 8.2, the account name in this case would be the string “Full Name.”Add the
kSecReturnAttributesattribute to the dictionary and set its value tokCFBooleanTrueif you want to retrieve the attributes, such as the creation and modification date, of the existing value in the keychain. If you want to retrieve the actual value of the item you stored in the keychain, instead of thekSecReturnAttributeskey, add thekSecReturnDatakey to your dictionary and set its value tokCFBooleanTrue.
Once your dictionary is ready, you can pass it as the first
parameter to the SecItemCopyMatching ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access