How to use ContactsGroups to create a contact group

I’ve tried a basic script to create a group of contacts.

If you encounter an error this might be because the container you are targeting is not iCloud.

In my specific case I had 2 containers: iCloud and a Google Exchange.
The later was the default group and do not support group creation.

You must be sure to target iCloud if you want to be able to properly create the group.

/** Create a group with single member in the specified container.
 */
function createGroup(container, groupName) {
  let group = new ContactsGroup();
  group.name = groupName;
  console.log(`Group id ${ group.identifier }`);
  ContactsGroup.add(group, container.identifier);
  ContactsGroup.update(group);
  Contact.persistChanges();
  console.log(`Group id after ${ group.identifier }`); 
  return group;
}

let group = createGroup(ContactsContainer.default(), "some new group");
console.log(`Created group ${ group.name }`);

Edit: 2018/11/02

I updated my function to create a group as follow to better handle the promise for persistChanges() as follow:

function createGroup(container, groupName) {
    let group = new ContactsGroup();
    group.name = groupName;

  ContactsGroup.add(group, container.identifier);
  ContactsGroup.update(group);

  Contact.persistChanges()
  .then((data) => {
    console.log(`Group id after ${ group.identifier }`);
    console.log(`Persist changes completed: ${ data }`);
  })
  .catch((error) => { console.log(`Error: ${error}`); });
  
  return group;
}

I had the following error in the console when targeting Google container. It fine with iCloud.

2018-11-02 13:28:23: Containers: Contacts, Card
2018-11-02 13:28:23: Attempted to create group “some new group” [object ContactsGroup]
2018-11-02 13:28:23: Error: Error: The operation couldn’t be completed. (Foundation._GenericObjCError error 0.)

Big thanks to Simon for this incredible tool and his help to solve my initial issue.

3 Likes