Kevin Mann
Kevin Mann

Reputation: 167

Swift grab "My Card" CNContact

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.

Upvotes: 7

Views: 2579

Answers (3)

imthath
imthath

Reputation: 1708

In case anyone is still looking, this is now possible via CNContactStore using this unifiedMeContactWithKeys(toFetch:) method. Supported in all apple platforms.

Upvotes: 0

Duncan Babbage
Duncan Babbage

Reputation: 20187

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]

Upvotes: 0

Michael Dautermann
Michael Dautermann

Reputation: 89559

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.

Upvotes: 0

Related Questions