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
kSecClass
key 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
kSecAttrService
key 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
kSecAttrAccount
key 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
kSecReturnAttributes
attribute to the dictionary and set its value tokCFBooleanTrue
if 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 thekSecReturnAttributes
key, add thekSecReturnData
key to your dictionary and set its value tokCFBooleanTrue
.
Once your dictionary is ready, you can pass it as the first
parameter to the SecItemCopyMatching ...
Get iOS 7 Programming Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.