0

I am fetching user's information like his name,phone number and email id from contacts.But it is only showing first contact number.IF a person has more than one contact number,it didnt show that second number.Can someone help?I am using this function where EVContactProtocol is part of Library

    func didChooseContacts(_ contacts: [EVContactProtocol]?) {
    var conlist : String = ""
    if let cons = contacts {
        for con in cons {

            if let fullname = con.fullname(),let email1 = con.email , let phoneNumber = con.phone {
                conlist += fullname + "\n"
                print("Full Name: ",fullname)
                print("Email: ",email1)
                print("Phone Number: ",phoneNumber)

            }


        }
        self.textView?.text = conlist
    } else {
        print("I got nothing")
    }
    let _ = self.navigationController?.popViewController(animated: true)

}

1 Answers1

1

You should try this:

import Contacts

class ViewController: UIViewController
{
    lazy var contacts: [CNContact] =
    {
        let contactStore = CNContactStore()
        let keysToFetch = [
            CNContactFormatter.descriptorForRequiredKeys(for: .fullName),
            CNContactEmailAddressesKey,
            CNContactPhoneNumbersKey] as [Any]

        // Get all the containers
        var allContainers: [CNContainer] = []
        do 
        {
            allContainers = try contactStore.containers(matching: nil)
        }
        catch 
        {
            print("Error fetching containers")
        }

        var results: [CNContact] = []

       // Iterate all containers and append their contacts to our results array
        for container in allContainers 
        {
            let fetchPredicate = CNContact.predicateForContactsInContainer(withIdentifier: container.identifier)

            do 
            {
                let containerResults = try contactStore.unifiedContacts(matching: fetchPredicate, keysToFetch: keysToFetch as! [CNKeyDescriptor])
                results.append(contentsOf: containerResults)
            } 
            catch 
            {
                print("Error fetching results for container")
            }
        }

    return results
    }()

    override func viewDidLoad()
    {
        super.viewDidLoad()
        print(contacts[0].givenName)
        print(contacts[0].phoneNumbers)
        print(contacts[0].emailAddresses)
        print(contacts)
    }
}
Pragnesh Vitthani
  • 2,532
  • 20
  • 28