【问题标题】:UNNotificationServiceExtension exit calling CNContactStore enumerateContactsUNNotificationServiceExtension 退出调用 CNContactStore enumerateContacts
【发布时间】:2018-04-09 21:49:46
【问题描述】:

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

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

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

我使用相同的代码在我的应用中查找电话号码,它运行良好。我还可以在没有问题的情况下替换通知扩展中的文本。仅当我尝试在扩展程序中调用 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!)
}

【问题讨论】:

  • 仍在寻找这个问题的答案。

标签: swift xcode cncontactstore


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2017-02-01
    • 2019-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多