How to fetch all contacts phone numbers

Hi all,


I am making an app which is fetching all contacts phone numbers.


From all contacts I am making a competition that people can make with their phone contacts.


Can someone advice how to fetch all phone numbers using CNContactStore?


Thanks,

Boban

Sure.

Fetching Contacts


For how to fetch the contacts: you may also check out the sample at Github (https://github.com/shinobicontrols/iOS9-day-by-day/tree/master/07-Contacts-Frame). If you just want to download this specific project, just open terminal and enter the following command:


svn export https://github.com/shinobicontrols/iOS9-day-by-day/trunk/07-Contacts-Framework ~/Downloads/Contacts-Framework


You will want to evaluate this specific function:


func findContacts () -> [CNContact]{

        let keysToFetch = [CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName),CNContactPhoneNumbersKey] /
        let fetchRequest = CNContactFetchRequest( keysToFetch: keysToFetch)
        var contacts = [CNContact]()

        fetchRequest.mutableObjects = false
        fetchRequest.unifyResults = true
        fetchRequest.sortOrder = .UserDefault

        let contactStoreID = CNContactStore().defaultContainerIdentifier()
        print("\(contactStoreID)")


        do {

            try CNContactStore().enumerateContactsWithFetchRequest(fetchRequest) { (contact, stop) -> Void in
                /
                contacts.append(contact)
            }
        } catch let e as NSError {
            print(e.localizedDescription)
        }

        return contacts

    }


Wrap this in a background thread for performance:


dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {  
            self.contacts = self.findContacts()  
             
            dispatch_async(dispatch_get_main_queue()) {  
               //update your UI somehow   
               //self.tableView!.reloadData()  
            }  
        }

Formatting the Phone Numbers:

You can just use this for a localized string of the iPhone number for example: (look up the other phone constant string types and assign each one of them with this method before you fetch the contacts)


CNContact.localizedStringForKey(CNLabelPhoneNumberiPhone)

More Info

You can also review the Contacts Framework WWDC video ()


If this resolves your question, please click the link below otherwise feel free to update the thread.

That only fetches the contacts in the default container. Is there a way to fetch all the contacts in the entire store using CNContactStore instance method enumerateContacts(with:usingBlock:)?

How to fetch all contacts phone numbers
 
 
Q