SPB Git

Repository Public

Notifier.swift 1.5 KB 34 lines swift

1import AppKit2import SettingsModel3import UserNotifications45/// Native notifications, only ever posted after the user enabled them and macOS granted permission.6@MainActor7final class Notifier {8    static let shared = Notifier()9    private var authorized = false1011    /// Asks macOS for permission. Called when the user turns notifications on in Settings.12    func requestAuthorization() async -> Bool {13        guard Bundle.main.bundleIdentifier != nil else { return false }14        let granted = (try? await UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound])) ?? false15        authorized = granted16        return granted17    }1819    func refreshAuthorization() async {20        let settings = await UNUserNotificationCenter.current().notificationSettings()21        authorized = settings.authorizationStatus == .authorized || settings.authorizationStatus == .provisional22    }2324    func post(title: String, body: String, settings: AppSettings, onlyWhenInactive: Bool) {25        guard settings.notifyOnLongCommand, authorized, !settings.privateMode else { return }26        if onlyWhenInactive, NSApp.isActive { return }27        let content = UNMutableNotificationContent()28        content.title = title29        // Never put terminal output in a notification: only process names and durations.30        content.body = body31        UNUserNotificationCenter.current().add(UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil))32    }33}34
Files main
Menu

Theme