UNNotificationServiceExtension fails accessing CNContactStore

I’m using the UNNotificationServiceExtension to replace a phone number with a name in a notification. I’m attempting to lookup the phone number in CNContactStore and replace the Ph# with the contact name.  (Same as iMessage notifications and other SMS text messages)

My issue is that when I call CNContactStore enumerateContacts(with: keysToFetch: ) the extension is exited without ever return from the enumerateContacts call.


If on the other hand I call CNContactStore’s unifiedContacts(matching: predicate, keysToFetch: keys) it returns as expected. Unfortunately, however, this call will not find a phone number. The only way I’ve found of looking up a phone number is to call enumerateContacts.


I use the same code to lookup phone numbers in my app and it works fine. I can also replace the text in the notification extension w/o issue. The problem only occurs when I try to call enumerateContacts inside the Extension.


override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
        let searchPhoneNumber = "5555551234"
        let keys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey] as [CNKeyDescriptor]
        let contactsStore = CNContactStore()
        do {
            try contactsStore.enumerateContacts(with: CNContactFetchRequest(keysToFetch: keys)) {
                (contact, error) -> Void in
                print("I'm back from enumerateContacts")
                if (!contact.phoneNumbers.isEmpty) {
                    for phoneNumber in contact.phoneNumbers {
                        if phoneNumber.value.stringValue == searchPhoneNumber {
                            self.bestAttemptContent?.body = contact.givenName
        catch {
            print("Unable to fetch contacts")

Powered by WPeMatico


You may also like...

Comments are closed.