Search code examples
iossqliteswift3cncontact

Fetching Contacts from mobile and store to sqliteDB using Swift 3


I am new in the Swift 3 language and I want to fetch contacts from the phone in an array and then store in sqliteDB. Please help.

I saw an old tutorial of Swift 2.1 but all these methods are deprecated and I tried a lot with CNContacts but this was not helpful for me.

I also tried this link of Stack Overflow but did not get any help:
Fetching all contacts in ios Swift?


Solution

  • I've just been working on a similar problem so i'll give you my code. I put it together from a few different threads I found (including this). Our requirement is to just get the phone number alone from all contacts and put it into a String array but you could easily modify this to do more:

    func getContacts(){
    
        contactStore.requestAccess(for: .contacts, completionHandler: {
            granted, error in
    
            var contacts: [CNContact] = {
                let contactStore = CNContactStore()
    
                //Change keys here to retreive more than just the phone number of the contact
                let keysToFetch = [CNContactPhoneNumbersKey]
    
                // Get all the containers
                var allContainers: [CNContainer] = []
                do {
                    allContainers = try contactStore.containers(matching: 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.predicateForContactsInContainer(withIdentifier: container.identifier)
    
                    do {
    
                        let containerResults = try contactStore.unifiedContacts(matching: fetchPredicate, keysToFetch: keysToFetch as [CNKeyDescriptor])
    
                        results.append(contentsOf: containerResults)
    
                        for phone in results{
    
                            for labeledValue in phone.phoneNumbers{
                                self.phoneNumbersArray.append(labeledValue.value.stringValue)
                            }
                        }
    
                    } catch {
                        print("Error fetching results for container")
                    }
                }
    
                return results
            }()
    
            self.getFriendsFromPhoneNumbers()
        })
    }
    

    This goes through all the containers and returns an array of CNObjects (with only the phone numbers inside but you can make it get more by just changing the keys) and then iterates through each Contact and label inside the array to insert just the phone numbers as Strings into a Phone Number array.