在过去的几天里,我偶然发现了这个困扰我的问题。
我有一个在蓝牙显示器上显示用户名的请求。我试图通过电话扩展来实现它,使用以下代码:
import Foundation
import CallKit
import CoreData
import PhoneNumberKit
class CallDirectoryHandler: CXCallDirectoryProvider {
private let sharedExtensionData = SharedExtensionData()
private let phoneNumberKit = PhoneNumberKit()
private func callers(includeHidden: Bool = false) throws -> [Caller] {
let fetchRequest: NSFetchRequest<Caller> = self.sharedExtensionData.fetchRequest(includeHidden: includeHidden)
fetchRequest.fetchBatchSize = 30
let callers = try self.sharedExtensionData.context.fetch(fetchRequest)
return callers
}
override func beginRequest(with context: CXCallDirectoryExtensionContext) {
context.delegate = self
if context.isIncremental {
addOrRemoveIncrementalIdentificationPhoneNumbers(to: context)
} else {
addAllIdentificationPhoneNumbers(to: context)
}
context.completeRequest()
}
private func addAllIdentificationPhoneNumbers(to context: CXCallDirectoryExtensionContext) {
if var callers = try? self.callers(includeHidden: false) {
callers = callers.sorted(by: { $0.number < $1.number })
let allPhoneNumbers = callers.map { $0.number }
let labels = callers.map { $0.name }
for (phoneNumber, label) in zip(allPhoneNumbers, labels) {
guard let number = try? phoneNumberKit.parse("\(phoneNumber)") else { return }
let formatedNumber = phoneNumberKit.format(number, toType: .e164) as NSString
let finalNumber = formatedNumber.longLongValue
autoreleasepool {
context.addIdentificationEntry(withNextSequentialPhoneNumber: finalNumber, label: label ?? "NO NAME")
}
}
}
}
private func addOrRemoveIncrementalIdentificationPhoneNumbers(to context: CXCallDirectoryExtensionContext) {
if var callers = try? self.callers(includeHidden: false) {
callers = callers.sorted(by: { $0.number < $1.number })
for caller in callers {
autoreleasepool {
guard let name = caller.name else { return }
if caller.isHidden {
context.removeIdentificationEntry(withPhoneNumber: caller.number)
} else {
context.addIdentificationEntry(withNextSequentialPhoneNumber: caller.number, label: name)
}
context.completeRequest()
}
}
}
}
}
extension CallDirectoryHandler: CXCallDirectoryExtensionContextDelegate {
func requestFailed(for extensionContext: CXCallDirectoryExtensionContext, withError error: Error) {
}
}
而且我还有以下代码正在检查是否启用了呼叫阻止和识别:
private func checkCallIdentificationPermission() {
CXCallDirectoryManager.sharedInstance.getEnabledStatusForExtension(withIdentifier: UMCConfiguration.callKitExtensionIdentifier.value ?? "MYEXTID") { [unowned self] (status, error) in
if let error = error {
logger.error("\(#function) \(error.localizedDescription)")
} else {
switch status {
case .unknown, .disabled:
self.showAlertToEnableCallblockingFeature()
default:
break
}
}
}
}
扩展中使用的数据模型也添加到呼叫扩展的构建阶段,但无论如何我仍然无法在汽车显示屏上看到用户名而不是数字?这个主题的文档很差,我会说根本不存在,所以欢迎任何提示。