iosswiftxcodeios12cncontactstore

Unable to fetch contacts using CNContactStore in iOS 12.4.1 (iPhone XR). Works well in even 13 beta or below 12.4.1


I am fetching contacts and displaying it using my custom UI. I am facing one weird issue, CNContactStore class does not give me contacts, It returns an empty array.

Below is my code.

let contactStore = CNContactStore()

let keysToFetch = [
        CNContactFormatter.descriptorForRequiredKeys(for: .fullName),
        CNContactGivenNameKey,
        CNContactMiddleNameKey,
        CNContactFamilyNameKey,
        CNContactPhoneNumbersKey
        ] as [Any]

    //Get all the containers
    var allContainers: [CNContainer] = []
    do {
        allContainers = try contactStore.containers(matching: nil)

    } catch let errorToShow{

        //Handling error
    }

My code is working for below 12.4.1 and in iOS 13 all beta versions. Right now I am testing it in iPhone XR.


Solution

  • I tried below code without doing any info.plist changes and it is working fine in iOS 13 and lower versions. (from iOS 13 we need to add key in plist in order to access Note, In my case, I do not want to do it).

     if let keysToFetch = [
                CNContactFormatter.descriptorForRequiredKeys(for: .fullName),CNContactGivenNameKey, CNContactMiddleNameKey,
                CNContactFamilyNameKey,CNContactPhoneNumbersKey] as? [CNKeyDescriptor]{
    
                let request = CNContactFetchRequest(keysToFetch: keysToFetch)
                do {
                    try contactStore.enumerateContacts(with: request){
                        (cont, stop) in
                        // Array containing all unified contacts from everywhere
    
                    }
    
                } catch let errorToShow{
    
                }
    
            }