Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Loop.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -752,6 +752,8 @@
8DC1CE32F39301122B550325 /* LoopKitTypeAliases.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35FAEFD820F50BFF211AC6D9 /* LoopKitTypeAliases.swift */; };
ABD9218EB98C9216FBB04382 /* LoopKitTypeAliases.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35FAEFD820F50BFF211AC6D9 /* LoopKitTypeAliases.swift */; };
AF79DFAB0F55143D66022668 /* LoopKitTypeAliases.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35FAEFD820F50BFF211AC6D9 /* LoopKitTypeAliases.swift */; };
DB2650000000000000000001 /* MealReminderManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = DB2650000000000000000002 /* MealReminderManager.swift */; };
DB2650000000000000000003 /* MealReminderManagerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DB2650000000000000000004 /* MealReminderManagerTests.swift */; };
/* End PBXBuildFile section */

/* Begin PBXContainerItemProxy section */
Expand Down Expand Up @@ -1628,6 +1630,8 @@
35FAEFD820F50BFF211AC6D9 /* LoopKitTypeAliases.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = LoopKitTypeAliases.swift; sourceTree = "<group>"; };
36421A4B9676EF68CDDC4ECD /* AlgorithmBridge.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AlgorithmBridge.swift; sourceTree = "<group>"; };
6C372374D3D3D9C5F8E3AD93 /* TemporaryScheduleOverrideAlgorithmTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TemporaryScheduleOverrideAlgorithmTests.swift; sourceTree = "<group>"; };
DB2650000000000000000002 /* MealReminderManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MealReminderManager.swift; sourceTree = "<group>"; };
DB2650000000000000000004 /* MealReminderManagerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MealReminderManagerTests.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */

/* Begin PBXFrameworksBuildPhase section */
Expand Down Expand Up @@ -1824,6 +1828,7 @@
C188599A2AF15E1B0010F21F /* DeviceDataManagerTests.swift */,
C16B983F26B4898800256B05 /* DoseEnactorTests.swift */,
E9C58A7124DB489100487A17 /* LoopDataManagerTests.swift */,
DB2650000000000000000004 /* MealReminderManagerTests.swift */,
A1B2C3D40000000000000001 /* GlucoseAlertManagerTests.swift */,
A1B2C3D40000000000000011 /* AlarmSoundCatalogTests.swift */,
E9B3552C293592B40076AB04 /* MealDetectionManagerTests.swift */,
Expand Down Expand Up @@ -2295,6 +2300,7 @@
A9D5C5B525DC6C6A00534873 /* LoopAppManager.swift */,
43A567681C94880B00334FAC /* LoopDataManager.swift */,
E9B355232935906B0076AB04 /* Missed Meal Detection */,
DB2650000000000000000002 /* MealReminderManager.swift */,
43C094491CACCC73001F6403 /* NotificationManager.swift */,
A97F250725E056D500F0EE19 /* OnboardingManager.swift */,
432E73CA1D24B3D6009AD15D /* RemoteDataServicesManager.swift */,
Expand Down Expand Up @@ -3810,6 +3816,7 @@
C9A47B0180AAB1FC572D3EFE /* CriticalAlertAudioPlayer.swift in Sources */,
C1A1A00001000000000000A1 /* CriticalAlertAlarmScheduler.swift in Sources */,
C9A47B0280AAB1FC572D3EFF /* GlucoseAlertManager.swift in Sources */,
DB2650000000000000000001 /* MealReminderManager.swift in Sources */,
43C0944A1CACCC73001F6403 /* NotificationManager.swift in Sources */,
149A28E42A8A63A700052EDF /* FavoriteFoodDetailView.swift in Sources */,
1DDE274024AEA4F200796622 /* NotificationsCriticalAlertPermissionsView.swift in Sources */,
Expand Down Expand Up @@ -4215,6 +4222,7 @@
E9B3552D293592B40076AB04 /* MealDetectionManagerTests.swift in Sources */,
C1DA43552B193BCB00CBD33F /* MockUploadEventListener.swift in Sources */,
C1DA43572B1A70BE00CBD33F /* SettingsManagerTests.swift in Sources */,
DB2650000000000000000003 /* MealReminderManagerTests.swift in Sources */,
1D8D55BC252274650044DBB6 /* BolusEntryViewModelTests.swift in Sources */,
C188599E2AF15FAB0010F21F /* AlertMocks.swift in Sources */,
A91E4C2124F867A700BE9213 /* StoredAlertTests.swift in Sources */,
Expand Down
11 changes: 8 additions & 3 deletions Loop/Managers/Alerts/AlertManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,11 @@ public final class AlertManager {
rescheduleLoopNotRunningNotifications()

Task {
do {
try await MealReminderManager.shared.updatePendingReminderSounds(newValue)
} catch {
log.error("Failed to update meal reminder sounds: %{public}@", String(describing: error))
}
do {
let persistedAlerts = try await lookupAllPendingDelayedOrRepeatingAlerts()
for persistedAlert in persistedAlerts {
Expand Down Expand Up @@ -879,14 +884,14 @@ extension AlertManager {
}
}

fileprivate extension UserDefaults {
extension UserDefaults {
private enum Key: String {
case hasIssuedNotificationPermissionsAlert = "com.loopkit.Loop.HasIssuedNotificationPermissionsAlert"
case hasIssuedScheduledDeliveryEnabledAlert = "com.loopkit.Loop.HasIssuedScheduledDeliveryEnabledAlert"
case alertMuterConfiguration = "com.loopkit.Loop.alertMuterConfiguration"
}

var hasIssuedNotificationPermissionsAlert: Bool {
fileprivate var hasIssuedNotificationPermissionsAlert: Bool {
get {
return object(forKey: Key.hasIssuedNotificationPermissionsAlert.rawValue) as? Bool ?? false
}
Expand All @@ -895,7 +900,7 @@ fileprivate extension UserDefaults {
}
}

var hasIssuedScheduledDeliveryEnabledAlert: Bool {
fileprivate var hasIssuedScheduledDeliveryEnabledAlert: Bool {
get {
return object(forKey: Key.hasIssuedScheduledDeliveryEnabledAlert.rawValue) as? Bool ?? false
}
Expand Down
20 changes: 20 additions & 0 deletions Loop/Managers/Alerts/UserNotificationAlertScheduler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,26 @@ public protocol UserNotificationCenter {
}
extension UNUserNotificationCenter: UserNotificationCenter {}

extension UserNotificationCenter {
func addNotificationRequest(_ request: UNNotificationRequest) async throws {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
add(request) { error in
if let error {
continuation.resume(throwing: error)
} else {
continuation.resume()
}
}
}
}

func pendingNotificationRequests() async -> [UNNotificationRequest] {
await withCheckedContinuation { continuation in
getPendingNotificationRequests { continuation.resume(returning: $0) }
}
}
}

public class UserNotificationAlertScheduler {

let userNotificationCenter: UserNotificationCenter
Expand Down
4 changes: 4 additions & 0 deletions Loop/Managers/LoopAppManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -952,6 +952,10 @@ extension LoopAppManager: @preconcurrency DeviceOrientationController {
extension LoopAppManager: UNUserNotificationCenterDelegate {

nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
if notification.request.content.categoryIdentifier == MealReminderManager.categoryIdentifier {
completionHandler([.sound, .list, .banner])
return
}
switch notification.request.identifier {
// TODO: Until these notifications are converted to use the new alert system, they shall still show in the foreground
case LoopNotificationCategory.bolusFailure.rawValue,
Expand Down
6 changes: 5 additions & 1 deletion Loop/Managers/LoopDataManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -594,7 +594,11 @@ extension LoopDataManager {

@discardableResult
func deleteCarbEntry(_ oldEntry: StoredCarbEntry) async throws -> Bool {
try await carbStore.deleteCarbEntry(oldEntry)
let deleted = try await carbStore.deleteCarbEntry(oldEntry)
if deleted {
MealReminderManager.shared.cancelReminder(for: oldEntry)
}
return deleted
}

/// Logs a new external bolus insulin dose in the DoseStore and HealthKit
Expand Down
136 changes: 136 additions & 0 deletions Loop/Managers/MealReminderManager.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
//
// MealReminderManager.swift
// Loop
//
// Copyright © 2026 LoopKit Authors. All rights reserved.
//

import Foundation
import LoopKit
import UserNotifications

enum MealReminderAction: Equatable {
case keep
case set
case clear
}

@MainActor
protocol MealReminderScheduling {
func hasPendingReminder(for entry: StoredCarbEntry) async -> Bool
func scheduleReminder(for entry: StoredCarbEntry, replacing original: StoredCarbEntry?) async throws
func cancelReminder(for entry: StoredCarbEntry)
}

/// The notification request persists across launches. Its identifier follows the carb
/// entry's sync identity, rather than the HealthKit UUID that changes on edits.
@MainActor
final class MealReminderManager: MealReminderScheduling {
static let shared = MealReminderManager()
nonisolated static let categoryIdentifier = "com.loopkit.Loop.MealReminder"
private static let mealTimeKey = "mealTime"

enum SchedulingError: Error {
case notificationsDisabled
case missingEntryIdentifier
}

private let notificationCenter: UserNotificationCenter
private let now: () -> Date
private let authorize: () async throws -> Bool
private let isMuted: (TimeInterval) -> Bool

init(
notificationCenter: UserNotificationCenter = UNUserNotificationCenter.current(),
now: @escaping () -> Date = Date.init,
authorize: @escaping () async throws -> Bool = {
let center = UNUserNotificationCenter.current()
var settings = await center.notificationSettings()
if settings.authorizationStatus == .notDetermined {
guard try await center.requestAuthorization(options: [.alert, .sound]) else { return false }
settings = await center.notificationSettings()
}
return settings.authorizationStatus != .denied && settings.alertSetting == .enabled
},
isMuted: @escaping (TimeInterval) -> Bool = {
UserDefaults.standard.alertMuterConfiguration.shouldMuteAlert(scheduledAt: $0)
}
) {
self.notificationCenter = notificationCenter
self.now = now
self.authorize = authorize
self.isMuted = isMuted
}

nonisolated static func requestIdentifier(for entry: StoredCarbEntry) -> String? {
guard let identifier = entry.syncIdentifier ?? entry.uuid?.uuidString else { return nil }
return "\(categoryIdentifier).\(entry.provenanceIdentifier).\(identifier)"
}

func hasPendingReminder(for entry: StoredCarbEntry) async -> Bool {
guard let identifier = Self.requestIdentifier(for: entry) else { return false }
let requests = await notificationCenter.pendingNotificationRequests()
return requests.contains { $0.identifier == identifier }
}

func scheduleReminder(for entry: StoredCarbEntry, replacing original: StoredCarbEntry? = nil) async throws {
guard entry.startDate > now() else {
cancelReminder(for: original ?? entry)
return
}
guard let identifier = Self.requestIdentifier(for: entry) else {
throw SchedulingError.missingEntryIdentifier
}
guard try await authorize() else { throw SchedulingError.notificationsDisabled }

// Authorization may have taken long enough for the meal time to pass.
let delay = entry.startDate.timeIntervalSince(now())
guard delay > 0 else {
cancelReminder(for: original ?? entry)
return
}

let content = UNMutableNotificationContent()
content.title = NSLocalizedString("Time to Eat", comment: "Title of a scheduled meal reminder")
let quantity = QuantityFormatter(for: .gram).string(from: entry.quantity) ?? ""
let time = DateFormatter.localizedString(from: entry.startDate, dateStyle: .none, timeStyle: .short)
content.body = String(format: NSLocalizedString("You entered %1$@ for %2$@. If your plans have changed, update your carb entry.", comment: "Meal reminder body (1: carb quantity with unit, 2: meal time)"), quantity, time)
content.categoryIdentifier = Self.categoryIdentifier
content.userInfo = [Self.mealTimeKey: entry.startDate.timeIntervalSince1970]
content.interruptionLevel = .timeSensitive
content.sound = isMuted(delay) ? nil : .default

let request = UNNotificationRequest(
identifier: identifier,
content: content,
trigger: UNTimeIntervalNotificationTrigger(timeInterval: delay, repeats: false)
)
try await notificationCenter.addNotificationRequest(request)
if let original, Self.requestIdentifier(for: original) != identifier {
cancelReminder(for: original)
}
notificationCenter.removeDeliveredNotifications(withIdentifiers: [identifier])
}

func cancelReminder(for entry: StoredCarbEntry) {
guard let identifier = Self.requestIdentifier(for: entry) else { return }
notificationCenter.removePendingNotificationRequests(withIdentifiers: [identifier])
notificationCenter.removeDeliveredNotifications(withIdentifiers: [identifier])
}

func updatePendingReminderSounds(_ configuration: AlertMuter.Configuration) async throws {
let requests = await notificationCenter.pendingNotificationRequests()
for request in requests where request.content.categoryIdentifier == Self.categoryIdentifier {
guard let timestamp = request.content.userInfo[Self.mealTimeKey] as? TimeInterval,
let content = request.content.mutableCopy() as? UNMutableNotificationContent else { continue }
let date = Date(timeIntervalSince1970: timestamp)
let currentTime = now()
let delay = date.timeIntervalSince(currentTime)
guard delay > 0 else { continue }
content.sound = configuration.shouldMuteAlert(scheduledAt: delay, now: currentTime) ? nil : .default
// Reusing the original interval trigger would postpone the reminder.
let updated = UNNotificationRequest(identifier: request.identifier, content: content, trigger: UNTimeIntervalNotificationTrigger(timeInterval: delay, repeats: false))
try await notificationCenter.addNotificationRequest(updated)
}
}
}
Loading