Search code examples
iosswiftcontactsaddressbook

CNPropertyNotFetchedException App Crashed


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.


Solution

  • 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