TheNoiseClock/TheNoiseClock/Services/NotificationService.swift
Matt Bruce 204aabf8d2 refactored
Signed-off-by: Matt Bruce <mbrucedogs@gmail.com>
2025-09-08 06:48:25 -05:00

81 lines
2.0 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 {
print("Error requesting notification permissions: \(error)")
isAuthorized = false
return false
}
}
func checkAuthorizationStatus() {
UNUserNotificationCenter.current().getNotificationSettings { settings in
DispatchQueue.main.async {
self.isAuthorized = settings.authorizationStatus == .authorized
}
}
}
func scheduleAlarmNotification(
id: String,
title: String,
body: String,
soundName: String,
date: Date
) async -> Bool {
guard isAuthorized else {
print("Notifications not authorized")
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
)
}
func cancelNotification(id: String) {
NotificationUtils.removeNotification(identifier: id)
}
func cancelAllNotifications() {
NotificationUtils.removeAllNotifications()
}
}