43 lines
1.6 KiB
Swift
43 lines
1.6 KiB
Swift
import Foundation
|
|
import UserNotifications
|
|
#if canImport(UIKit)
|
|
import UIKit
|
|
#endif
|
|
|
|
/// Manages local UNUserNotificationCenter notifications for download events.
|
|
@MainActor
|
|
final class NotificationManager {
|
|
static let shared = NotificationManager()
|
|
private init() {}
|
|
|
|
/// Requests notification authorization the first time the app launches.
|
|
/// Skips the system prompt if permission has already been granted or denied.
|
|
func requestPermissionIfNeeded() async {
|
|
let center = UNUserNotificationCenter.current()
|
|
let settings = await center.notificationSettings()
|
|
guard settings.authorizationStatus == .notDetermined else { return }
|
|
_ = try? await center.requestAuthorization(options: [.alert, .sound])
|
|
}
|
|
|
|
/// Fires a local notification when a download fails.
|
|
/// Suppressed while the app is in the foreground — an in-app alert already
|
|
/// surfaces the error there, so a notification would be redundant.
|
|
func sendDownloadFailedNotification(itemTitle: String) async {
|
|
#if canImport(UIKit)
|
|
guard UIApplication.shared.applicationState != .active else { return }
|
|
#endif
|
|
|
|
let content = UNMutableNotificationContent()
|
|
content.title = "Download fehlgeschlagen"
|
|
content.body = "„\(itemTitle)" konnte nicht heruntergeladen werden."
|
|
content.sound = .default
|
|
|
|
let request = UNNotificationRequest(
|
|
identifier: "download-failed-\(UUID().uuidString)",
|
|
content: content,
|
|
trigger: nil // deliver immediately
|
|
)
|
|
try? await UNUserNotificationCenter.current().add(request)
|
|
}
|
|
}
|