0

我正在从联系人中获取用户的信息,例如他的姓名、电话号码和电子邮件 ID。但它只显示第一个联系号码。如果一个人有多个联系号码,它没有显示第二个号码。有人可以帮忙吗?我正在使用这个函数,其中 EVContactProtocol 是库的一部分

    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)

}
4

1 回答 1

1

你应该试试这个:

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)
    }
}
于 2017-05-05T11:59:32.873 回答