iosswiftxcodeios-contactscncontainer

How do I set the default contacts container for my iOS app to the contacts container that is saved in iCloud?


I am writing an iOS app using Swift and Xcode 13.1. I am using the Contacts Framework, and I read that each app has a default contacts container, and the default container in an app can be different than the default container in another app, and there is not a default container for the entire device.

What determines which is the default container for the app made by an Xcode project? I didn't set the default container for my app and somehow the contacts container for a Google account became the default contacts container for my app. How do I use code to set the default contacts container for my app?

How do I find out which is the default container of Apple's Contacts app that comes with iOS? I would like to set my app's default contacts container to the same default container of Apple's Contacts app, if that is the contacts container that is saved on iCloud. If not, I would like to set my app's default contacts container to the contacts container that is saved in iCloud. I assume that only one contacts container is saved on iCloud.


Solution

  • The user can specify the default contact container for new contacts in settings. Your app can access the identifier of this container using defaultContainerIdentifier.

    If you want to allow the user to specify a different container for new contacts created by your app, then you need to code that yourself.

    You need to provide a view that displays the list of contact containers resulting from a call to containers(matching:nil). Once the user selects a container, store its identifier in your apps preferences and use that container identifier when you create new contacts.

    All you can know about a container is its identifier, its name and its type (Exchange, CalDAV or local).