Why can't I retrieve the groups from the default container of Apple iOS Contacts Framework?

215 views Asked by At

I have an iOS app that accesses the default container of the contact store and retrieves the groups within that container. After I signed out of my iPhone 8 device that the app is installed in, and then signed in with another account. Then signed out and signed in with my original account, the app was no longer able to retrieve the groups from the default container.

Why is it doing this and how do I fix this?

Here is the relevant code:

cnGroups = try contactStore.groups(matching: CNGroup.predicateForGroupsInContainer(withIdentifier: contactStore.defaultContainerIdentifier()))

print("cnGroups...")
print(cnGroups)

Here is the debug window output:

cnGroups...
[]

I initialized the contact store globally in a swift file outside of any class:

internal var contactStore = CNContactStore()

This code to request access to Contacts from the user is in the viewDidLoad() callback method. The initUTIGroups() method is where I try to retrieve the groups from the default container.

contactStore.requestAccess(for: .contacts) {

    permissionGranted, error in

    if error != nil {

        print(error?.localizedDescription as Any)

    }

    if permissionGranted {

        self.initUTIGroups()

    } else {

        let alertMessage = "\(displayName) will not work unless you allow access to Contacts. Please go to Settings and allow access to Contacts then restart \(displayName)"

        let alert = UIAlertController(title: nil, message: alertMessage, preferredStyle: .alert)

        let actionOK = UIAlertAction(title: "OK", style: .cancel, handler: nil)

        alert.addAction(actionOK)

        self.present(alert, animated: true, completion: nil)

    }

}

I retrieved all the containers in the contact store and I compared them with the default container. It looks like the current default container is not the same container as the default container before I signed out of iCloud the first time. I found the container that contains the groups, which are the same groups that I retrieved from the default container before I signed out of iCloud the first time.

Is there code I can write that would prevent the problem or fix the problem once it occurs?

0

There are 0 answers