Files
kangkang/康康/Services/ReminderService.swift
link2026 7ad41c5f09 ```
docs(health-profile): 添加防编造加固修订记录到导出健康档案设计文档

补充了关于导出摘要出现虚构病例问题的详细分析和修复方案,
包括检索策略优化、空数据兜底处理和prompt重写等三层防护措施。
```
2026-05-30 20:06:12 +08:00

157 lines
6.5 KiB
Swift

import Foundation
import UserNotifications
///
/// `metricId` iOS N weekly-repeats ,id
/// `kangkang.reminder.<metricId>.w<weekday>`,便 weekday cancel
///
/// SwiftData `MetricReminder`;,
/// SwiftData
enum ReminderService {
static let idPrefix = "kangkang.reminder."
static let customIdPrefix = "kangkang.custom."
enum AuthState: String {
case granted, denied, notDetermined, provisional
}
// MARK: - authorization
static func currentAuthState() async -> AuthState {
let settings = await UNUserNotificationCenter.current().notificationSettings()
switch settings.authorizationStatus {
case .authorized: return .granted
case .denied: return .denied
case .provisional: return .provisional
case .ephemeral: return .granted
case .notDetermined: return .notDetermined
@unknown default: return .notDetermined
}
}
/// granted/denied
@discardableResult
static func requestAuthorization() async -> AuthState {
let center = UNUserNotificationCenter.current()
let settings = await center.notificationSettings()
if settings.authorizationStatus != .notDetermined {
return await currentAuthState()
}
do {
let granted = try await center.requestAuthorization(options: [.alert, .sound, .badge])
return granted ? .granted : .denied
} catch {
return .denied
}
}
// MARK: - upsert / cancel
/// metric pending , enabled//weekdays
/// `MetricReminder` save
static func sync(_ reminder: MetricReminder) async {
cancel(metricId: reminder.metricId)
guard reminder.enabled else { return }
let slots = reminder.weekdays.map { wd in
Slot(suffix: "w\(wd)",
dc: DateComponents(hour: reminder.hour, minute: reminder.minute, weekday: wd))
}
await schedule(
idBase: "\(idPrefix)\(reminder.metricId)",
title: String(appLoc: "该测\(reminder.displayName)"),
body: String(appLoc: "在「+ 新建 → 指标记录 → \(reminder.displayName)」记录一次"),
thread: "kangkang.reminder.\(reminder.metricId)",
slots: slots
)
}
/// metric pending (7 weekday ,)
static func cancel(metricId: String) {
cancelBase("\(idPrefix)\(metricId)")
}
// MARK: - (CustomReminder)
/// `CustomReminder` save
static func sync(_ reminder: CustomReminder) async {
cancel(customId: reminder.id)
guard reminder.enabled else { return }
let title = reminder.title.trimmingCharacters(in: .whitespacesAndNewlines)
let body = reminder.note.trimmingCharacters(in: .whitespacesAndNewlines)
let h = reminder.hour, m = reminder.minute
let slots: [Slot]
switch reminder.frequency {
case .daily:
slots = [Slot(suffix: "daily", dc: DateComponents(hour: h, minute: m))]
case .weekly:
slots = reminder.weekdays.map { wd in
Slot(suffix: "w\(wd)", dc: DateComponents(hour: h, minute: m, weekday: wd))
}
case .monthly:
slots = [Slot(suffix: "monthly",
dc: DateComponents(day: reminder.dayOfMonth, hour: h, minute: m))]
case .yearly:
slots = [Slot(suffix: "yearly",
dc: DateComponents(month: reminder.month, day: reminder.dayOfMonth, hour: h, minute: m))]
}
await schedule(
idBase: "\(customIdPrefix)\(reminder.id.uuidString)",
title: title.isEmpty ? String(appLoc: "提醒") : title,
body: body.isEmpty ? String(appLoc: "到点啦,记得完成") : body,
thread: "\(customIdPrefix)\(reminder.id.uuidString)",
slots: slots
)
}
/// pending
static func cancel(customId: UUID) {
cancelBase("\(customIdPrefix)\(customId.uuidString)")
}
/// Me Tab
static func cancelAll() {
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
}
// MARK: -
/// :`suffix` id(`<idBase>.<suffix>`,
/// `.daily` / `.w2` / `.monthly` / `.yearly`),`dc`
private struct Slot {
let suffix: String
let dc: DateComponents
}
/// `Slot` N repeats ///
private static func schedule(idBase: String,
title: String,
body: String,
thread: String,
slots: [Slot]) async {
guard !slots.isEmpty else { return }
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = .default
content.threadIdentifier = thread
for slot in slots {
let trigger = UNCalendarNotificationTrigger(dateMatching: slot.dc, repeats: true)
let request = UNNotificationRequest(identifier: "\(idBase).\(slot.suffix)",
content: content,
trigger: trigger)
try? await center.add(request)
}
}
/// idBase pending (daily/monthly/yearly + 7 weekday,)
private static func cancelBase(_ idBase: String) {
let center = UNUserNotificationCenter.current()
var ids = ["\(idBase).daily", "\(idBase).monthly", "\(idBase).yearly"]
ids += (1...7).map { "\(idBase).w\($0)" }
center.removePendingNotificationRequests(withIdentifiers: ids)
}
}