SPB Git

Repository Public License

SleepReminders.swift 3.1 KB 63 lines swift

1// ORIX Alarm2// File: App/Features/Sleep/SleepReminders.swift3// Description: Evening wind-down and bedtime reminders as repeating daily local notifications (identifiers namespaced "sleep.").4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import Foundation9import UserNotifications1011enum SleepReminders {12    /// What the app may do with notifications, reduced to what the sleep planner needs.13    enum Permission: Sendable { case notDetermined, allowed, denied }1415    /// Every identifier this feature may have scheduled.16    static let identifiers = SleepPlanner.Reminder.Kind.allCases.map { "sleep." + $0.rawValue }1718    static func permission() async -> Permission {19        switch await UNUserNotificationCenter.current().notificationSettings().authorizationStatus {20        case .authorized, .provisional, .ephemeral: .allowed21        case .denied: .denied22        default: .notDetermined23        }24    }2526    /// Asks for the notification permission. Call only when the user turns reminders on.27    static func requestPermission() async -> Permission {28        let current = await permission()29        guard current == .notDetermined else { return current }30        let granted = (try? await UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound])) ?? false31        return granted ? .allowed : .denied32    }3334    /// Makes the pending local notifications match the plan (none when the plan or its reminders are off).35    /// Never asks for permission: without it, nothing is scheduled.36    static func sync(plan: SleepPlan) async {37        let center = UNUserNotificationCenter.current()38        center.removePendingNotificationRequests(withIdentifiers: identifiers)39        let reminders = SleepPlanner.reminders(for: plan)40        guard !reminders.isEmpty, await permission() == .allowed else { return }41        for reminder in reminders {42            let content = UNMutableNotificationContent()43            switch reminder.kind {44            case .windDown:45                content.title = String(localized: "Time to wind down")46                content.body = String(localized: "Your planned bedtime is in \(SleepFmt.span(plan.windDownMinutes)). Start your evening routine.")47            case .bedtime:48                content.title = String(localized: "Bedtime")49                content.body = String(localized: "This is the bedtime you planned. Going to bed now leaves \(SleepFmt.span(plan.opportunityMinutes)) in bed before your wake time.")50            }51            content.sound = .default52            content.threadIdentifier = "sleep"53            let trigger = UNCalendarNotificationTrigger(dateMatching: DateComponents(hour: reminder.time.hour, minute: reminder.time.minute), repeats: true)54            try? await center.add(UNNotificationRequest(identifier: reminder.id, content: content, trigger: trigger))55        }56    }5758    /// Identifiers of the sleep reminders currently pending in the system (for display and tests).59    static func pendingIdentifiers() async -> [String] {60        await UNUserNotificationCenter.current().pendingNotificationRequests().map(\.identifier).filter { $0.hasPrefix("sleep.") }.sorted()61    }62}63
Files main
Menu

Theme