Fetching all contacts in ios Swift?

后端 未结 7 1412
天命终不由人
天命终不由人 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:21

    Many answers to Contact Framework questions suggest iterating over various containers (accounts). However, Apple's documentation describes a "Unified Contact" as

    Contacts in different accounts that represent the same person may be automatically linked together. Linked contacts are displayed in OS X and iOS apps as unified contacts. A unified contact is an in-memory, temporary view of the set of linked contacts that are merged into one contact.

    By default the Contacts framework returns unified contacts. Each fetched unified contact (CNContact) object has its own unique identifier that is different from any individual contact’s identifier in the set of linked contacts. A refetch of a unified contact should be done with its identifier. Source

    So simplest way to fetch a list of (partial, based on keys) contacts in a single array, would be the following:

        var contacts = [CNContact]()
        let keys = [CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName)]
        let request = CNContactFetchRequest(keysToFetch: keys)
    
        do {
            try self.contactStore.enumerateContactsWithFetchRequest(request) {             
                (contact, stop) in
                // Array containing all unified contacts from everywhere
                contacts.append(contact)
            }
        } 
        catch {
            print("unable to fetch contacts")
        }
    

提交回复
热议问题