您如何快速从用户联系人访问电话号码? [英] How do you access a phone number from your user's contacts in swift?

查看:69
本文介绍了您如何快速从用户联系人访问电话号码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我获取联系人姓名的代码,我该如何获取他们的电话号码?

Here is my code for getting the name of a contact, how would I go about getting their phone number?

func createAddressBook() -> Bool {
    if self.addressBook != nil {
        return true
    }
    var err : Unmanaged<CFError>? = nil
    let addressBook : ABAddressBook? = ABAddressBookCreateWithOptions(nil, &err).takeRetainedValue()
    if addressBook == nil {
        println(err)
        self.addressBook = nil
        return false
    }
    self.addressBook = addressBook
    getContactNames()
    return true
}

func getContactNames() {
    if !self.determineStatus() {
        println("not authorized")
        return
    }
    let people = ABAddressBookCopyArrayOfAllPeople(addressBook).takeRetainedValue() as NSArray as [ABRecord]
    for person in people {
        var contactName = ABRecordCopyCompositeName(person).takeRetainedValue() as String
        self.contacts.append(contact(name: contactName))
    }
}

任何帮助将不胜感激.

推荐答案

从iOS 9开始,我们将使用Contacts框架,其中 phoneNumbers CNLabeledValue< CNPhoneNumber> :

As of iOS 9, we would use Contacts framework, in which phoneNumbers is a CNLabeledValue<CNPhoneNumber>:

let status = CNContactStore.authorizationStatus(for: .contacts)
if status == .denied || status == .restricted {
    presentSettingsAlert()
    return
}

// open it

let store = CNContactStore()
store.requestAccess(for: .contacts) { granted, error in
    guard granted else {
        self.presentSettingsAlert()
        return
    }
    
    // get the contacts
    
    let request = CNContactFetchRequest(keysToFetch: [CNContactFormatter.descriptorForRequiredKeys(for: .fullName), CNContactPhoneNumbersKey as CNKeyDescriptor])
    do {
        try store.enumerateContacts(with: request) { contact, stop in
            let name = CNContactFormatter.string(from: contact, style: .fullName)
            print(name)
            
            for phone in contact.phoneNumbers {
                var label = phone.label
                if label != nil {
                    label = CNLabeledValue<CNPhoneNumber>.localizedString(forLabel: label!)
                }
                print("  ", label, phone.value.stringValue)
            }
        }
    } catch {
        print(error)
    }
}

哪里

private func presentSettingsAlert() {
    let settingsURL = URL(string: UIApplicationOpenSettingsURLString)!
    
    DispatchQueue.main.async {
        let alert = UIAlertController(title: "Permission to Contacts", message: "This app needs access to contacts in order to ...", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Go to Settings", style: .default) { _ in
            UIApplication.shared.openURL(settingsURL)
        })
        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
        self.present(alert, animated: true)
    }
}


在iOS 9之前,您将使用AddressBook框架,其中电话号码是 ABMultiValueRef ,因此请获取该引用,然后遍历电话号码:


Prior to iOS 9, you would use the AddressBook framework, in which the phone numbers is a ABMultiValueRef, so get that reference and then iterate through the phone numbers:

// make sure user hadn't previously denied access

let status = ABAddressBookGetAuthorizationStatus()
if status == .denied || status == .restricted {
    presentSettingsAlert()
    return
}

// open it

var error: Unmanaged<CFError>?
guard let addressBook: ABAddressBook? = ABAddressBookCreateWithOptions(nil, &error)?.takeRetainedValue() else {
    print(String(describing: error?.takeRetainedValue()))
    return
}

// request permission to use it

ABAddressBookRequestAccessWithCompletion(addressBook) { granted, error in
    if !granted {
        self.presentSettingsAlert()
        return
    }
    
    guard let people = ABAddressBookCopyArrayOfAllPeople(addressBook)?.takeRetainedValue() as [ABRecord]? else {
        print("unable to get contacts")
        return
    }
    
    for person in people {
        let name = ABRecordCopyCompositeName(person)?.takeRetainedValue() as String?
        print(name)
        
        if let phoneNumbers: ABMultiValue = ABRecordCopyValue(person, kABPersonPhoneProperty)?.takeRetainedValue() {
            for index in 0 ..< ABMultiValueGetCount(phoneNumbers) {
                let number = ABMultiValueCopyValueAtIndex(phoneNumbers, index)?.takeRetainedValue() as? String
                let label  = ABMultiValueCopyLabelAtIndex(phoneNumbers, index)?.takeRetainedValue()
                print("  ", self.localizedLabel(label), number)
            }
        }
    }
}

MacOS有一个用于对该标签进行本地化的现有例程,但是我不知道iOS的AddressBook框架中有任何此类公共功能,因此您可能需要自己进行转换(或为 NSLocalizedString填充本地化表):

MacOS has an existing routine to localize that label, but I don't know of any such public function in AddressBook framework for iOS, so you may want to convert it yourself (or populate localization table for NSLocalizedString):

// frankly, you probably should just use `NSLocalizedString()` and fill the table with these values

private func localizedLabel(_ label: CFString?) -> String? {
    guard let label = label else {
        return nil
    }
    
    if CFStringCompare(label, kABHomeLabel, []) == .compareEqualTo {            // use `[]` for options in Swift 2.0
        return "Home"
    } else if CFStringCompare(label, kABWorkLabel, []) == .compareEqualTo {
        return "Work"
    } else if CFStringCompare(label, kABOtherLabel, []) == .compareEqualTo {
        return "Other"
    } else if CFStringCompare(label, kABPersonPhoneMobileLabel, []) == .compareEqualTo {
        return "Mobile"
    } else if CFStringCompare(label, kABPersonPhoneIPhoneLabel, []) == .compareEqualTo {
        return "iPhone"
    } else if CFStringCompare(label, kABPersonPhoneMainLabel, []) == .compareEqualTo {
        return "Main"
    } else if CFStringCompare(label, kABPersonPhoneHomeFAXLabel, []) == .compareEqualTo {
        return "Home fax"
    } else if CFStringCompare(label, kABPersonPhoneWorkFAXLabel, []) == .compareEqualTo {
        return "Work fax"
    } else if CFStringCompare(label, kABPersonPhoneOtherFAXLabel, []) == .compareEqualTo {
        return "Other fax"
    } else if CFStringCompare(label, kABPersonPhonePagerLabel, []) == .compareEqualTo {
        return "Pager"
    } else {
        return label as String
    }
}

对于Swift 2,请参见此答案的先前版本.

For Swift 2, see previous revision of this answer.

这篇关于您如何快速从用户联系人访问电话号码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆