Arun V
Arun V

Reputation: 63

How to retrieve the contact number in ios 9

in ios 8, i used the below code to print the user's contact Number,

if let contacts = ABAddressBookCopyArrayOfAllPeople(self.addressBookRef)?.takeRetainedValue() as? NSArray {
            for record:ABRecordRef in contacts {

                let phones:ABMultiValueRef = ABRecordCopyValue(record, kABPersonPhoneProperty).takeUnretainedValue() as ABMultiValueRef
                for(var numberIndex : CFIndex = 0; numberIndex < ABMultiValueGetCount(phones); numberIndex++)
                {
                    let phoneUnmaganed = ABMultiValueCopyValueAtIndex(phones, numberIndex)
                    let phoneNumber : String = phoneUnmaganed.takeUnretainedValue() as! String

println(phoneNumber) } }

But apple introduced new contact framework in ios 9. Now i stuck with retrieving contact number. I found some code in the apple site and in other sites as given below, But still it's not exactly printing only the contact numbers,

contacts = try store.unifiedContactsMatchingPredicate(
                CNContact.predicateForContactsMatchingName("Siva"),
                keysToFetch:[CNContactPhoneNumbersKey])
            for contact:CNContact in contacts {
                if (contact.isKeyAvailable(CNContactPhoneNumbersKey)) {
                    for phoneNumber:CNLabeledValue in contact.phoneNumbers {
                        print(phoneNumber.value)
                    }
                }

Upvotes: 6

Views: 4467

Answers (1)

Mathias Navne
Mathias Navne

Reputation: 246

This should do it.

        if (contact.isKeyAvailable(CNContactPhoneNumbersKey)) {
            for phoneNumber:CNLabeledValue in contact.phoneNumbers {
                let a = phoneNumber.value as! CNPhoneNumber
                print("\(a.stringValue)")
            }
        }

prints in the style of (555) 766-4823

Upvotes: 21

Related Questions