2024-11-12 10:17:29 +08:00

164 lines
6.4 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// CallProcessor.swift
// NotificationServiceExtension
//
// Created by huangfeng on 2024/6/6.
// Copyright © 2024 Fin. All rights reserved.
//
import AudioToolbox
import Foundation
class CallProcessor: NotificationContentProcessor {
///
var soundID: SystemSoundID = 0
/// content
var content: UNMutableNotificationContent? = nil
/// APP
var needsStop = false
func process(identifier: String, content bestAttemptContent: UNMutableNotificationContent) async throws -> UNMutableNotificationContent {
guard let call = bestAttemptContent.userInfo["call"] as? String, call == "1" else {
return bestAttemptContent
}
self.content = bestAttemptContent
self.registerObserver()
self.sendLocalNotification(identifier: identifier, content: bestAttemptContent)
self.cancelRemoteNotification(content: bestAttemptContent)
await startAudioWork()
return bestAttemptContent
}
func serviceExtensionTimeWillExpire(contentHandler: (UNNotificationContent) -> Void) {
stopAudioWork()
if let content {
contentHandler(content)
}
}
///
private func sendLocalNotification(identifier: String, content: UNMutableNotificationContent) {
// id使APNS
guard let content = content.mutableCopy() as? UNMutableNotificationContent else {
return
}
if !content.isCritical { //
content.sound = nil
}
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: nil)
UNUserNotificationCenter.current().add(request)
}
///
private func cancelRemoteNotification(content: UNMutableNotificationContent) {
//
// iOS15
// level level
if #available(iOSApplicationExtension 15.0, *), self.content?.userInfo["level"] == nil {
self.content?.interruptionLevel = .passive
}
}
// startAudioWork(completion:)
private func startAudioWork() async {
return await withCheckedContinuation { continuation in
self.startAudioWork {
continuation.resume()
}
}
}
///
var startAudioWorkCompletion: (() -> Void)? = nil
///
private func startAudioWork(completion: @escaping () -> Void) {
guard let content else {
completion()
return
}
self.startAudioWorkCompletion = completion
let sound = ((content.userInfo["aps"] as? [String: Any])?["sound"] as? String)?.split(separator: ".")
let soundName: String
let soundType: String
if sound?.count == 2, let first = sound?.first, let last = sound?.last {
soundName = String(first)
soundType = String(last)
} else {
soundName = "multiwayinvitation"
soundType = "caf"
}
//
guard let audioPath = getSoundInCustomSoundsDirectory(soundName: "\(soundName).\(soundType)") ??
Bundle.main.path(forResource: soundName, ofType: soundType)
else {
completion()
return
}
let fileUrl = URL(string: audioPath)
//
AudioServicesCreateSystemSoundID(fileUrl! as CFURL, &soundID)
//
AudioServicesPlayAlertSound(soundID)
//
let selfPointer = unsafeBitCast(self, to: UnsafeMutableRawPointer.self)
AudioServicesAddSystemSoundCompletion(soundID, nil, nil, { sound, clientData in
guard let pointer = clientData else { return }
let processor = unsafeBitCast(pointer, to: CallProcessor.self)
if processor.needsStop {
processor.startAudioWorkCompletion?()
return
}
//
AudioServicesPlayAlertSound(sound)
}, selfPointer)
}
///
private func stopAudioWork() {
AudioServicesRemoveSystemSoundCompletion(soundID)
AudioServicesDisposeSystemSoundID(soundID)
}
///
func registerObserver() {
let notification = CFNotificationCenterGetDarwinNotifyCenter()
let observer = Unmanaged.passUnretained(self).toOpaque()
CFNotificationCenterAddObserver(notification, observer, { _, pointer, _, _, _ in
guard let observer = pointer else { return }
let processor = Unmanaged<CallProcessor>.fromOpaque(observer).takeUnretainedValue()
processor.needsStop = true
}, kStopCallProcessorKey as CFString, nil, .deliverImmediately)
}
func getSoundInCustomSoundsDirectory(soundName: String) -> String? {
// 访APP
guard let soundsDirectoryUrl = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.bark")?.appendingPathComponent("Sounds") else {
return nil
}
let path = soundsDirectoryUrl.appendingPathComponent(soundName).path
if FileManager.default.fileExists(atPath: path) {
return path
}
return nil
}
deinit {
let observer = Unmanaged.passUnretained(self).toOpaque()
let name = CFNotificationName(kStopCallProcessorKey as CFString)
CFNotificationCenterRemoveObserver(CFNotificationCenterGetDarwinNotifyCenter(), observer, name, nil)
}
}
extension UNMutableNotificationContent {
var isCritical: Bool {
if #available(iOS 15, *) {
return self.interruptionLevel == .critical
}
return false
}
}