I can't seem to figure out how to grab a users "My Card" from contacts. I am developing a native Mac application using swift.
-
1you are looking for CNContactStore @selector(unifiedMeContactWithKeysToFetch:error:) – Marek H Oct 23 '15 at 15:18
2 Answers
It's not from (the brand new as of MacOS 10.11) CNContact, but MacOS's ABAddressBook framework has a method called me()
which will return the logged in user's ABPerson record.
And to get the vCard equivalent, call vCardRepresentation()
on that ABPerson object.
The nice thing about the above solution is that it will work on older MacOS versions (e.g. MacOS 10.9, 10.10).
Marek points out the unifiedMeContactWithKeysToFetch:
API in CNContactStore, but at the time of me typing this answer, it's only documented in the .h header file in the SDK and not in the CNContactStore documentation.

- 88,797
- 17
- 166
- 215
-
CNContactStore is the place where to get CNContact from. There is "me" contact as well. Basically if you don't save contact there your app will crash but that's a different topic – Marek H Oct 23 '15 at 15:20
-
Thanks for noticing that @marekh ; I only see five hits on that API in Google today. – Michael Dautermann Oct 23 '15 at 17:13
-
1If it's in the header file, you can use it. Sometimes the documentation lags behind the header files. (Try to find the function reference documentation for Core Audio. Go on. I dare you.) – rob mayoff Oct 23 '15 at 20:15
-
There is a CNContact api for this, but it is only available in macOS 10.11+, and not in iOS of any version to date.
(For iOS, reverting to ABAddressBook does not solve the problem, as the me()
method there is likewise only for MacOS, though back as far as macOS 10.2+.)
import Contacts
let nameKeys = [
CNContactNamePrefixKey,
CNContactGivenNameKey,
CNContactMiddleNameKey,
CNContactFamilyNameKey,
CNContactNameSuffixKey,
] as [CNKeyDescriptor]
do {
let contactStore = CNContactStore()
let me = try contactStore.unifiedMeContactWithKeys(toFetch: nameKeys)
} catch let error {
print("Failed to retreive Me contact: \(error)")
}
Could of course also fetch additional keys:
let allContactKeys = [
CNContactNamePrefixKey,
CNContactGivenNameKey,
CNContactMiddleNameKey,
CNContactFamilyNameKey,
CNContactNameSuffixKey,
CNContactOrganizationNameKey,
CNContactDepartmentNameKey,
CNContactJobTitleKey,
CNContactBirthdayKey,
CNContactNicknameKey,
CNContactNoteKey,
CNContactNonGregorianBirthdayKey,
CNContactPreviousFamilyNameKey,
CNContactPhoneticGivenNameKey,
CNContactPhoneticMiddleNameKey,
CNContactPhoneticFamilyNameKey,
CNContactImageDataKey,
CNContactThumbnailImageDataKey,
CNContactImageDataAvailableKey,
CNContactTypeKey,
CNContactPhoneNumbersKey,
CNContactEmailAddressesKey,
CNContactPostalAddressesKey,
CNContactDatesKey,
CNContactUrlAddressesKey,
CNContactRelationsKey,
CNContactSocialProfilesKey,
CNContactInstantMessageAddressesKey,
] as [CNKeyDescriptor]

- 19,972
- 4
- 56
- 93