ios中的联系人选择器以获取电话号码

Posted

技术标签:

【中文标题】ios中的联系人选择器以获取电话号码【英文标题】:Contact picker in ios to get phone number 【发布时间】:2018-08-20 11:08:09 【问题描述】:

我需要一个像图像选择器这样的选项来选择联系人并显示我已经设法使用以下代码获取联系人姓名的电话号码

通过使用此代码,它只返回名称,需要从联系人列表中选择联系人的选项

【问题讨论】:

【参考方案1】:

导入ContactsUI 并包括 - CNContactPickerDelegate

import ContactsUI

class YourViewController: CNContactPickerDelegate

    //MARK:- contact picker
    func onClickPickContact()


        let contactPicker = CNContactPickerViewController()
        contactPicker.delegate = self
        contactPicker.displayedPropertyKeys =
            [CNContactGivenNameKey
                , CNContactPhoneNumbersKey]
        self.present(contactPicker, animated: true, completion: nil)

    

    func contactPicker(_ picker: CNContactPickerViewController,
                       didSelect contactProperty: CNContactProperty) 

    

    func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) 
        // You can fetch selected name and number in the following way

        // user name
        let userName:String = contact.givenName

        // user phone number
        let userPhoneNumbers:[CNLabeledValue<CNPhoneNumber>] = contact.phoneNumbers
        let firstPhoneNumber:CNPhoneNumber = userPhoneNumbers[0].value


        // user phone number string
        let primaryPhoneNumberStr:String = firstPhoneNumber.stringValue

        print(primaryPhoneNumberStr)

    

    func contactPickerDidCancel(_ picker: CNContactPickerViewController) 

    

【讨论】:

【参考方案2】:
import ContactsUI

private let contactPicker = CNContactPickerViewController()

启动联系人选择器的按钮点击:

@IBAction func accessContacts(_ sender: Any) 
    contactPicker.delegate = self
    self.present(contactPicker, animated: true, completion: nil)

实现委托方法

extension YourViewController: CNContactPickerDelegate 

    func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) 
        let phoneNumberCount = contact.phoneNumbers.count

        guard phoneNumberCount > 0 else 
            dismiss(animated: true)
            //show pop up: "Selected contact does not have a number"
            return
        

        if phoneNumberCount == 1 
            setNumberFromContact(contactNumber: contact.phoneNumbers[0].value.stringValue)

         else 
            let alertController = UIAlertController(title: "Select one of the numbers", message: nil, preferredStyle: .alert)

            for i in 0...phoneNumberCount-1 
                let phoneAction = UIAlertAction(title: contact.phoneNumbers[i].value.stringValue, style: .default, handler: 
                alert -> Void in
                    self.setNumberFromContact(contactNumber: contact.phoneNumbers[i].value.stringValue)
                )
                alertController.addAction(phoneAction)
            
            let cancelAction = UIAlertAction(title: "Cancel", style: .destructive, handler: 
            alert -> Void in

            )
            alertController.addAction(cancelAction)

            dismiss(animated: true)
            self.present(alertController, animated: true, completion: nil)
        
    

    func setNumberFromContact(contactNumber: String) 

        //UPDATE YOUR NUMBER SELECTION LOGIC AND PERFORM ACTION WITH THE SELECTED NUMBER

        var contactNumber = contactNumber.replacingOccurrences(of: "-", with: "")
        contactNumber = contactNumber.replacingOccurrences(of: "(", with: "")
        contactNumber = contactNumber.replacingOccurrences(of: ")", with: "")
        contactNumber = contactNumber.removeWhitespacesInBetween()
        guard contactNumber.count >= 10 else 
            dismiss(animated: true) 
                self.popUpMessageError(value: 10, message: "Selected contact does not have a valid number")
            
            return
        
        textFieldNumber.text = String(contactNumber.suffix(10))

    

    func contactPickerDidCancel(_ picker: CNContactPickerViewController) 

    

【讨论】:

【参考方案3】:

您可以使用此扩展来获取联系人姓名。

extension CNContact 
    open func displayName() -> String 
        return givenName + " " + familyName
    

这是获取一些详细信息的课程EPContact

【讨论】:

【参考方案4】:

Swift 5 & 联系人选择器获取电子邮件

我想展示一个示例,说明您如何做与您要求的相同的事情,而不是电子邮件,并为 Swift 5 更新,因为上面的一些答案没有正确编译。这还有一个额外的好处是'all'选项,如果用户选择它,它将把多封电子邮件连接成一个字符串。

首先确保导入import ContactsUI

然后确保您的文本字段有一个出口。

@IBOutlet var emailTextField: UITextField!

接下来,您需要将联系人选择器设置为 viewController 的成员变量。这将保存稍后显示联系人选择器的信息。

class EmailViewController: UIViewController 
    @IBOutlet var emailTextField: UITextField!
    private let contactPicker = CNContactPickerViewController()

    //... rest of view controller code, etc...

最后,您可以使用以下代码将此扩展添加到 EmailViewController:

extension EmailViewController: CNContactPickerDelegate 

    func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) 
        let emailNumberCount = contact.emailAddresses.count

        //@JA - They have to have at least 1 email address
        guard emailNumberCount > 0 else 
            dismiss(animated: true)
            //show pop up: "Selected contact does not have a number"
            let alertController = UIAlertController(title: "No emails found for contact: "+contact.givenName+" "+contact.familyName, message: nil, preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "Ok", style: .default, handler: 
            alert -> Void in

            )
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
            return
        

        //@JA - If they have only 1 email it's easy.  If there is many emails we want to concatenate them and separate by commas , , ...
        if emailNumberCount == 1 
            setEmailFromContact(contactEmail: contact.emailAddresses[0].value as String)
         else 
            let alertController = UIAlertController(title: "Select an email from contact: "+contact.givenName+" "+contact.familyName+" or select 'All' to send to every email listed.", message: nil, preferredStyle: .alert)

            for i in 0...emailNumberCount-1 
                let emailAction = UIAlertAction(title: contact.emailAddresses[i].value as String, style: .default, handler: 
                alert -> Void in
                    self.setEmailFromContact(contactEmail: contact.emailAddresses[i].value as String)
                )
                alertController.addAction(emailAction)
            

            let allAction = UIAlertAction(title: "All", style: .destructive, handler: 
            alert -> Void in
                var emailConcat = ""
                for i in 0...emailNumberCount-1
                    if(i != emailNumberCount-1) //@JA - Only add the , if we are not on the last item of the array
                        emailConcat = emailConcat + (contact.emailAddresses[i].value as String)+","
                    else
                        emailConcat = emailConcat + (contact.emailAddresses[i].value as String)
                    
                
                self.setEmailFromContact(contactEmail: emailConcat)//@JA - Sends the concatenated version of the emails separated by commas
            )
            alertController.addAction(allAction)

            let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: 
            alert -> Void in

            )
            alertController.addAction(cancelAction)

            dismiss(animated: true)
            self.present(alertController, animated: true, completion: nil)
        
    

    func setEmailFromContact(contactEmail: String)
        emailTextField.text = contactEmail
    

    func contactPickerDidCancel(_ picker: CNContactPickerViewController) 
        print("contact picker canceled")
    

例如,要在按钮的操作事件中调用选择器,您可以这样做:

@IBAction func contactsButtonPressed(_ sender: UIButton) 
     contactPicker.delegate = self
     self.present(contactPicker, animated: true, completion: nil)

contactPicker.delegate = self 之所以有效,是因为在我的例子中 viewController 类 (emailViewController) 上的扩展允许它访问它所需的 CNContactPickerDelegate 协议函数。

【讨论】:

以上是关于ios中的联系人选择器以获取电话号码的主要内容,如果未能解决你的问题,请参考以下文章

如何在 iOS 中选择联系人电话号码?

从 Android 中的 URI 检索联系人电话号码

从电话联系人中获取姓名、电话号码和电子邮件地址[关闭]

搜索联系人并从android中的电话联系人中获取联系人号码

Xamarin Android,使用带有选择和选择参数的 CursorLoader 获取联系人手机号码

从联系人选择器中获取号码