Search code examples
iosswiftcncontact

how to retrive all CNContactStore from device without filter


I'm trying to insert into var contacts: [CNContact] = [] the var store = CNContactStore() but I did not find the right code for this job, i found this function that I need to give that a name

func findContactsWithName(name: String) {
    AppDelegate.sharedDelegate().checkAccessStatus({ (accessGranted) -> Void in
        if accessGranted {
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                do {
                    let predicate: NSPredicate = CNContact.predicateForContactsMatchingName(name)
                    let keysToFetch = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactBirthdayKey, CNContactViewController.descriptorForRequiredKeys()]
                    self.contacts = try self.store.unifiedContactsMatchingPredicate(predicate, keysToFetch:keysToFetch)


                    self.tableView.reloadData()
                }
                catch {
                    print("Unable to refetch the selected contact.")
                }
            })
        }
    })
}

I want to insert self.contacts all the records and not only one with name equal


Solution

  • Update

    Based on comment from OP, please try the following CNContactFetchRequest-based API to retrieve all contacts without a filter. I run this on a background thread to reduce any possible issues huge numbers of contacts.

    func findContactsOnBackgroundThread ( completionHandler:(contacts:[CNContact]?)->()) {
    
            dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), { () -> Void in
    
                let keysToFetch = [CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName),CNContactPhoneNumbersKey] //CNContactIdentifierKey
                let fetchRequest = CNContactFetchRequest( keysToFetch: keysToFetch)
                var contacts = [CNContact]()
                CNContact.localizedStringForKey(CNLabelPhoneNumberiPhone)
    
                fetchRequest.mutableObjects = false
                fetchRequest.unifyResults = true
                fetchRequest.sortOrder = .UserDefault
    
                let contactStoreID = CNContactStore().defaultContainerIdentifier()
                print("\(contactStoreID)")
    
    
                do {
    
                    try CNContactStore().enumerateContactsWithFetchRequest(fetchRequest) { (contact, stop) -> Void in
                        //do something with contact
                        if contact.phoneNumbers.count > 0 {
                            contacts.append(contact)
                        }
    
                    }
                } catch let e as NSError {
                    print(e.localizedDescription)
                }
    
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    completionHandler(contacts: contacts)
    
                })
            })
        }
    

    Generally speaking you would normally set a predicate to nil to retrieve all of the contacts when using CNContactFetchRequest class rather than as described in your code.

    Note

    If you want to use your existing API then I recommend setting the predicate to true:

     NSPredicate(value: true)
    

    This should make all contacts return. If that does not work consider switching to the CNConctactFetchRequest API to enumerate the Contacts. In that event you could then set the predicate to nil to fetch all contacts (using CNConctactFetchRequest).

    CNContactFetch-Predicate

    This is how you might modify the existing method:

    func findContacts()->[CNContact] {
            AppDelegate.sharedDelegate().checkAccessStatus({ (accessGranted) -> Void in
                if accessGranted {
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        do {
                            let predicate: NSPredicate = NSPredicate(value: true)
                            let keysToFetch = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactBirthdayKey, CNContactViewController.descriptorForRequiredKeys()]
                            self.contacts = try self.store.unifiedContactsMatchingPredicate(predicate, keysToFetch:keysToFetch)
    
    
                            self.tableView.reloadData()
                        }
                        catch {
                            print("Unable to refetch the selected contact.")
                        }
                    })
                }
            })
        }
    

    And to use:

    let contacts = findContacts()
    

    Apple has a simpler sample:

    let store = CNContactStore()
    let contacts = try store.unifiedContactsMatchingPredicate(CNContact.predicateForContactsMatchingName("Appleseed"), keysToFetch:[CNContactGivenNameKey, CNContactFamilyNameKey])
    

    For your use-case, you could try to modify the Apple Sample like this:

    //Use the reference to look up additional keys constants that you may want to fetch
    let store = CNContactStore()
    let contacts = try store.unifiedContactsMatchingPredicate(NSPredicate(value: true), keysToFetch:[CNContactGivenNameKey, CNContactFamilyNameKey])
    

    More Apple Samples for the Contacts Framework