Search code examples
ioscncontactstore

Removing an iOS contact group


Anyone tried to remove an existing contact group using the iOS 9 Contacts framework?

I initialize the contact store and request the list of contact groups, which gives me an array of CNGroup instances:

var groups: [CNGroup]?

do {
    self.groups = try contactStore.groupsMatchingPredicate(nil)
}
catch { ... }

and then I show the groups in a table view. When the user swipes a table view cell, I would like to delete the corresponding group from the contact store.

However, the deleteGroup method of CNContactStore requires a CNMutableGroup instance, not a CNGroup. Xcode gives me an error:

Cannot convert value of type 'CNGroup' to expected type 'CNMutableGroup'

Obviously, if I try to cast the CNGroup instance to a CNMutableGroup:

let saveRequest = CNSaveRequest()
saveRequest.deleteGroup(group as! CNMutableGroup)
do {
    try contactStore.executeSaveRequest(saveRequest)
}
catch { ... }

I get a crash at runtime:

Could not cast value of type 'CNGroup' (0x370890f8) to 'CNMutableGroup' (0x370899f4)

I realize that this is because CNGroup is a superclass of CNMutableGroup, but then again I can't see how to get a CNMutableGroup initialized with a CNGroup instance.

I have requested access to the Contacts framework. Xcode 7.3, iOS 9.2.1.

So, any ideas on how to delete a contact group?


Solution

  • Casting a mutable copy of the CNGroup fixes this.

    let saveRequest = CNSaveRequest()
    saveRequest.deleteGroup(group.mutableCopy() as! CNMutableGroup)
    do {
        try contactStore.executeSaveRequest(saveRequest)
    }
    catch { ... }