87 lines
2.2 KiB
Swift
87 lines
2.2 KiB
Swift
//
|
|
// NotificationService.swift
|
|
// TheNoiseClock
|
|
//
|
|
// Created by Matt Bruce on 9/7/25.
|
|
//
|
|
|
|
import Foundation
|
|
import UserNotifications
|
|
import Observation
|
|
|
|
/// Service for managing system notifications
|
|
@Observable
|
|
class NotificationService {
|
|
|
|
// MARK: - Properties
|
|
private(set) var isAuthorized = false
|
|
|
|
// MARK: - Initialization
|
|
init() {
|
|
checkAuthorizationStatus()
|
|
}
|
|
|
|
// MARK: - Public Interface
|
|
func requestPermissions() async -> Bool {
|
|
do {
|
|
let granted = try await UNUserNotificationCenter.current().requestAuthorization(
|
|
options: [.alert, .sound, .badge]
|
|
)
|
|
isAuthorized = granted
|
|
return granted
|
|
} catch {
|
|
DebugLogger.log("Error requesting notification permissions: \(error)", category: .general)
|
|
isAuthorized = false
|
|
return false
|
|
}
|
|
}
|
|
|
|
func checkAuthorizationStatus() {
|
|
UNUserNotificationCenter.current().getNotificationSettings { settings in
|
|
DispatchQueue.main.async {
|
|
self.isAuthorized = settings.authorizationStatus == .authorized
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Schedule a single alarm notification
|
|
@discardableResult
|
|
func scheduleAlarmNotification(
|
|
id: String,
|
|
title: String,
|
|
body: String,
|
|
soundName: String,
|
|
date: Date
|
|
) async -> Bool {
|
|
guard isAuthorized else {
|
|
DebugLogger.log("Notifications not authorized", category: .settings)
|
|
return false
|
|
}
|
|
|
|
let content = NotificationUtils.createAlarmContent(
|
|
title: title,
|
|
body: body,
|
|
soundName: soundName
|
|
)
|
|
let trigger = NotificationUtils.createCalendarTrigger(for: date)
|
|
|
|
return await NotificationUtils.scheduleNotification(
|
|
identifier: id,
|
|
content: content,
|
|
trigger: trigger
|
|
)
|
|
}
|
|
|
|
|
|
/// Cancel a single notification
|
|
func cancelNotification(id: String) {
|
|
NotificationUtils.removeNotification(identifier: id)
|
|
}
|
|
|
|
/// Cancel all notifications
|
|
func cancelAllNotifications() {
|
|
NotificationUtils.removeAllNotifications()
|
|
}
|
|
|
|
}
|