如何在iOS 9中检索联系人电话号码

6
在iOS 8中,我使用以下代码来打印用户的联系电话:
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) } }

但是苹果在iOS 9中引入了新的联系人框架。现在我卡在了检索联系人号码上。我在苹果网站和其他网站上找到了一些代码,如下所示,但仍然没有准确地打印出联系人号码:

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)
                    }
                }

请帮我检索所有联系人的电话号码。 - Arun V
1个回答

21

这应该就可以了。

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

以 (555) 766-4823 的风格打印


store.unifiedContactsMatchingPredicate( CNContact.predicateForContactsMatchingName("Siva") , 我只想获取所有联系人。但是这行代码只能帮助我们获取Siva的联系人详细信息。你有什么建议吗?提前致谢。 - Arun V

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接