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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With