0

我正在使用 UNNotificationServiceExtension 将电话号码替换为通知中的名称。我正在尝试在 CNContactStore 中查找电话号码并将 Ph# 替换为联系人姓名。

我的问题是,当我调用 CNContactStore enumerateContacts(with: keysToFetch: )时,扩展程序会退出,而不会从enumerateContacts调用中返回。

另一方面,如果我调用 CNContactStore 的UnifiedContacts(matching: predicate, keysToFetch: keys)它会按预期返回。但是,不幸的是,此呼叫找不到电话号码。我发现查找电话号码的唯一方法是调用enumerateContacts

我使用相同的代码在我的应用程序中查找电话号码,它工作正常。我还可以在没有问题的情况下替换通知扩展中的文本。仅当我尝试在 Extension中调用enumerateContacts时才会出现此问题。

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("We never get here!!!")
            if (!contact.phoneNumbers.isEmpty) {

                for phoneNumber in contact.phoneNumbers {
                    if phoneNumber.value.stringValue == searchPhoneNumber {
                        // swap number for name
                        self.bestAttemptContent?.body = contact.givenName
                        contentHandler(self.bestAttemptContent!)
                        return
                    }
                }
            }
        }
    }
    catch {
        print("And we never get here.")
        contentHandler(bestAttemptContent!)
        return
    }
    contentHandler(bestAttemptContent!)
}
4

1 回答 1

0

来自 UNNotificationServiceExtension https://developer.apple.com/documentation/usernotifications/unnotificationserviceextension

该方法执行其任务和执行提供的完成块的时间有限。如果您的方法没有及时完成,系统会调用 serviceExtensionTimeWillExpire() 方法给您最后一次提交更改的机会。如果您未在时间到期前更新通知内容,系统将显示原始内容。

我猜想循环访问联系人超过了该方法完成的分配时间。

于 2018-10-15T11:54:06.383 回答