Fetching all contacts in ios Swift?

后端 未结 7 1398
天命终不由人
天命终不由人 2020-11-30 20:00

I am aware of the ios swift has a Contacts Framework where I can fetch contacts, but I cannot find any method to fetch all the contacts together where I can access each of t

相关标签:
7条回答
  • 2020-11-30 20:30

    Update for Swift 4

    let contactStore = CNContactStore()
    var contacts = [CNContact]()
    let keys = [
            CNContactFormatter.descriptorForRequiredKeys(for: .fullName),
                    CNContactPhoneNumbersKey,
                    CNContactEmailAddressesKey
            ] as [Any]
    let request = CNContactFetchRequest(keysToFetch: keys as! [CNKeyDescriptor])
    do {
        try contactStore.enumerateContacts(with: request){
                (contact, stop) in
            // Array containing all unified contacts from everywhere
            contacts.append(contact)
            for phoneNumber in contact.phoneNumbers {
                if let number = phoneNumber.value as? CNPhoneNumber, let label = phoneNumber.label {
                    let localizedLabel = CNLabeledValue<CNPhoneNumber>.localizedString(forLabel: label)
                    print("\(contact.givenName) \(contact.familyName) tel:\(localizedLabel) -- \(number.stringValue), email: \(contact.emailAddresses)")
                }
            }
        }
        print(contacts)
    } catch {
        print("unable to fetch contacts")
    }
    
    0 讨论(0)
提交回复
热议问题