Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IOS - CNContactPickerViewController should display only the names that has an email?

I just want to get the name and email from the mobile contact and print it. I'm using the following code to do this task.

import UIKit
import ContactsUI
class ViewController: UIViewController, CNContactPickerDelegate{

        override func viewDidLoad() {
            super.viewDidLoad()

        }

        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()

        }


        @IBAction func button(_ sender: Any)
        {
            let contactPicker = CNContactPickerViewController()
            contactPicker.delegate = self
            contactPicker.displayedPropertyKeys =
                [CNContactNicknameKey
                  ,CNContactEmailAddressesKey]

            self.present(contactPicker, animated: true, completion: nil)

        }
        func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact)
        {
            if let emailValue : CNLabeledValue = contact.emailAddresses.first
            {
                print(emailValue.value as String)
            }

            print(contact.givenName + " " + contact.familyName)

        }
    }

It prints the name and email that I select in CNContactPickerViewController, even if the selected name does not have an email, it just prints the name alone. Now, what i want is, I don't want to display the names that has no email, in the CNContactPickerViewController. Only names that has email stored along with it, should be displayed. How can i do that ?

Using Xcode 8.2, Swift 3, IOS 10

NOTE: I don't want to check whether the email exists or not, or is it valid or not.

like image 463
Tester Avatar asked Feb 24 '17 13:02

Tester


1 Answers

Have you tried adding a predicate to the CNContactPickerViewController? The documentation appears to have exactly the requirement that you're looking for.

In your button() method add the following before calling present().

contactPicker.predicateForEnablingContact = NSPredicate(format: "emailAddresses.@count > 0")
like image 177
Maarut Avatar answered Oct 24 '22 08:10

Maarut