gpt4 book ai didi

swift - UNNotificationServiceExtension 退出调用 CNContactStore enumerateContacts

转载 作者:行者123 更新时间:2023-11-30 11:36:13 26 4
gpt4 key购买 nike

我正在使用 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!)
}

最佳答案

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

That method has a limited amount of time to perform its task and execute the provided completion block. If your method does not finish in time, the system calls the serviceExtensionTimeWillExpire() method to give you one last chance to submit your changes. If you don't update the notification content before time expires, the system displays the original content.

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

关于swift - UNNotificationServiceExtension 退出调用 CNContactStore enumerateContacts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49742192/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com