如何在swift 4中从iPhone获取联系人列表?

时间:2018-01-02 12:10:36

标签: ios swift swift4

以下是我提取联系人列表的代码:

let contactStore = CNContactStore()
    let keys = [CNContactPhoneNumbersKey, CNContactFamilyNameKey, CNContactGivenNameKey, CNContactNicknameKey, CNContactPhoneNumbersKey]
    let request1 = CNContactFetchRequest(keysToFetch: keys  as [CNKeyDescriptor])

    try? contactStore.enumerateContacts(with: request1) { (contact, error) in
        for phone in contact.phoneNumbers {
            // Whatever you want to do with it
        }
    }

1 个答案:

答案 0 :(得分:0)

lazy var contacts: [CNContact] = {
    let contactStore = CNContactStore()
    let keysToFetch = [
        CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName),
        CNContactEmailAddressesKey,
        CNContactPhoneNumbersKey,
        CNContactImageDataAvailableKey,
        CNContactThumbnailImageDataKey]

    // Get all the containers
    var allContainers: [CNContainer] = []
    do {
        allContainers = try contactStore.containersMatchingPredicate(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.predicateForContactsInContainerWithIdentifier(container.identifier)

        do {
             let containerResults = try     contactStore.unifiedContactsMatchingPredicate(fetchPredicate, keysToFetch: keysToFetch)
            results.appendContentsOf(containerResults)
        } catch {
            print("Error fetching results for container")
        }
    }

    return results
}()