7

i want to get the all contacts list of phone with their name as well as phone numbers in swift 3.0 and xcode 8.0. below is the code

func get_all_user_contacts()
{
    let status = CNContactStore.authorizationStatus(for: .contacts)
    if status == .denied || status == .restricted
    {
        presentSettingsActionSheet()
        return
    }

    // open it

    let store = CNContactStore()
    store.requestAccess(for: .contacts) { granted, error in
        guard granted else
        {
            DispatchQueue.main.async {
                self.presentSettingsActionSheet()
            }
            return
        }

        // get the contacts

        var contacts = [CNContact]()

        let request = CNContactFetchRequest(keysToFetch: [CNContactIdentifierKey as NSString, CNContactFormatter.descriptorForRequiredKeys(for: .fullName)])
        do
        {
            try store.enumerateContacts(with: request)
            { contact, stop in


                contacts.append(contact)
            }
        }
        catch
        {
            print(error)
        }

        // do something with the contacts array (e.g. print the names)

        let formatter = CNContactFormatter()
        formatter.style = .fullName
        for contact in contacts
        {
            let MobNumVar  = ((contact.phoneNumbers.first?.value)! as CNPhoneNumber).stringValue
            print(MobNumVar)
            print(formatter.string(from: contact) ?? "???")
        }
    }
}

when i run this app it crashes and i don't know where i am getting wrong. anyone can help me out.. it will be appreciated.

Alpha
  • 167
  • 1
  • 13

1 Answers1

15

You're requesting keys

• CNContactIdentifierKey
• CNContactFormatter.descriptorForRequiredKeys(for: .fullName)

…but then you're trying to access contact.phoneNumber.

You can only access keys specified in keysToFetch, so you need to add CNContactPhoneNumbersKey to that array

Ashley Mills
  • 50,474
  • 16
  • 129
  • 160
  • yes. u are right. but can u help me out more that how i can add this to an array. ??? some piece of code.. thnx – Alpha Mar 30 '17 at 07:33
  • 1
    it works. i added: CNContactPhoneNumbersKey as CNKeyDescriptor – Alpha Mar 30 '17 at 10:25
  • The crux of this is you need to fetch the properties you're testing in the predicate as well as any other properties you want. – Rick Feb 13 '19 at 01:18