2025-01-17 11:13:51 +08:00

72 lines
2.7 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.

//
// LevelProcessor.swift
// NotificationServiceExtension
//
// Created by huangfeng on 2024/5/29.
// Copyright © 2024 Fin. All rights reserved.
//
import Foundation
///
class LevelProcessor: NotificationContentProcessor {
func process(identifier: String, content bestAttemptContent: UNMutableNotificationContent) async throws -> UNMutableNotificationContent {
guard let level = bestAttemptContent.userInfo["level"] as? String else {
return bestAttemptContent
}
if let level = bestAttemptContent.userInfo["level"] as? String, level == "critical" {
//
LevelProcessor.setCriticalSound(content: bestAttemptContent)
return bestAttemptContent
}
//
guard #available(iOSApplicationExtension 15.0, *) else {
return bestAttemptContent
}
let interruptionLevels: [String: UNNotificationInterruptionLevel] = [
"passive": UNNotificationInterruptionLevel.passive,
"active": UNNotificationInterruptionLevel.active,
"timeSensitive": UNNotificationInterruptionLevel.timeSensitive,
"timesensitive": UNNotificationInterruptionLevel.timeSensitive
]
bestAttemptContent.interruptionLevel = interruptionLevels[level] ?? .active
return bestAttemptContent
}
}
extension LevelProcessor {
class func setCriticalSound(content bestAttemptContent: UNMutableNotificationContent, soundName: String? = nil) {
guard let level = bestAttemptContent.userInfo["level"] as? String, level == "critical" else {
return
}
//
var audioVolume: Float = 0.5
// 0 - 10 , 0.0 - 1.0
if let volume = bestAttemptContent.userInfo["volume"] as? String, let volume = Float(volume) {
audioVolume = max(0.0, min(1, volume / 10.0))
}
// sound
let sound = soundName ?? bestAttemptContent.soundName
if let sound {
bestAttemptContent.sound = UNNotificationSound.criticalSoundNamed(UNNotificationSoundName(rawValue: sound), withAudioVolume: audioVolume)
} else {
bestAttemptContent.sound = UNNotificationSound.defaultCriticalSound(withAudioVolume: audioVolume)
}
}
}
extension UNMutableNotificationContent {
///
var isCritical: Bool {
self.userInfo["level"] as? String == "critical"
}
///
var soundName: String? {
(self.userInfo["aps"] as? [AnyHashable: Any])?["sound"] as? String
}
}