commit 19e89268b30d36e4f7cb7cbab1a2b98e0b524424
parent 0106daafc5e6ceb194ecfdd1285edf76bdf9c855
Author: Michael Camilleri <[email protected]>
Date: Tue, 20 Oct 2026 10:40:00 +0900
Move notification settings to separate screen
Diffstat
| M | Reportage.xcodeproj/project.pbxproj | | | 4 | ++++ |
| A | Reportage/Views/Settings/NotificationsView.swift | | | 271 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| M | Reportage/Views/Settings/SettingsView.swift | | | 258 | +++++-------------------------------------------------------------------------- |
3 files changed, 289 insertions(+), 244 deletions(-)
diff --git a/Reportage.xcodeproj/project.pbxproj b/Reportage.xcodeproj/project.pbxproj
@@ -10,6 +10,7 @@
013407A07B79F11D51E23BD1 /* Theme.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C7B68925A281EF806BB9B8 /* Theme.swift */; };
047D3797389624E8B4AF44B4 /* ReportageExporter.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD433A98973E8B13E42230A1 /* ReportageExporter.swift */; };
06415D2A2EDA6E92ECAC96FA /* Report.swift in Sources */ = {isa = PBXBuildFile; fileRef = B03734F91822E7F161432075 /* Report.swift */; };
+ 06BD386D5CA144F8D5053A39 /* NotificationsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F832E0B277D5BF5BC3B6E5D1 /* NotificationsView.swift */; };
0F052B8A2C73437F57E927E7 /* ReportStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84E55C093BA98D8700F406AE /* ReportStoreTests.swift */; };
123470F9E3205890526D3A89 /* EventLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = BFF717BC324925C231BD3378 /* EventLog.swift */; };
16CDDFE25EBB07C0EA9AC5AA /* DiagnosticsSection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 87545A7909A370C668314DFF /* DiagnosticsSection.swift */; };
@@ -222,6 +223,7 @@
E7F1ECC4B803EFFD88FFF52B /* ReportageExport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportageExport.swift; sourceTree = "<group>"; };
EC2D996880DB9C269F0203D5 /* AppleWeather.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppleWeather.swift; sourceTree = "<group>"; };
F498961A14F24AE6CC37453C /* ReportDetailView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportDetailView.swift; sourceTree = "<group>"; };
+ F832E0B277D5BF5BC3B6E5D1 /* NotificationsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotificationsView.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXGroup section */
@@ -461,6 +463,7 @@
children = (
CA2E66BAB2463FD51EFE9F52 /* DataSection.swift */,
87545A7909A370C668314DFF /* DiagnosticsSection.swift */,
+ F832E0B277D5BF5BC3B6E5D1 /* NotificationsView.swift */,
7F9A0A87A54F3E96E079F52D /* QuestionsView.swift */,
81BA515BEA1B0B68CE0D1326 /* SettingsView.swift */,
);
@@ -704,6 +707,7 @@
3244B8439B5E4F79FF84C156 /* JSONSlicer.swift in Sources */,
6F06CC539C4D17B343A9321C /* LegacyBlob.swift in Sources */,
BDEB83CDBA9E0B4DB7712491 /* LogPassiveReportIntent.swift in Sources */,
+ 06BD386D5CA144F8D5053A39 /* NotificationsView.swift in Sources */,
D1F2257DDB68439AF352B57D /* PassiveLog.swift in Sources */,
C5D94FEC4507054E6497E85B /* PersistenceController.swift in Sources */,
2EE68329C383FA1C5295ACA9 /* PlaceAnswerView.swift in Sources */,
diff --git a/Reportage/Views/Settings/NotificationsView.swift b/Reportage/Views/Settings/NotificationsView.swift
@@ -0,0 +1,271 @@
+import CoreLocation
+import SwiftUI
+import UserNotifications
+
+/// When random prompts come: how many, between which hours and how far
+/// apart.
+struct NotificationsView: View {
+ @Environment(\.reportStore) private var store
+ @Environment(\.scenePhase) private var scenePhase
+ @State private var settings = PromptSettings.load()
+ @State private var notifications: UNAuthorizationStatus?
+ @State private var location: CLAuthorizationStatus?
+ /// Counts finished reschedules, so the debug list of pending
+ /// notifications reloads after each.
+ @State private var scheduleGeneration = 0
+
+ private static let gaps = [0, 15, 30, 45, 60, 90, 120]
+ private static let snoozes = [5, 10, 15, 20, 30, 60]
+
+ var body: some View {
+ List {
+ Section {
+ Toggle("Random Prompts", isOn: promptsEnabled)
+ .settingsRow()
+ .listRowSeparator(.hidden, edges: .top)
+ if settings.isEnabled {
+ Stepper(value: $settings.perDay, in: 1...12) {
+ LabeledContent("Prompts a Day") {
+ Text(settings.perDay, format: .number)
+ .monospacedDigit()
+ }
+ }
+ .settingsRow()
+ }
+ SettingsNote { promptsFooter }
+ }
+ if settings.isEnabled {
+ Section {
+ WindowPicker(window: $settings.window)
+ Toggle("Different Hours on Weekends", isOn: hasWeekendWindow)
+ .settingsRow()
+ SettingsNote {
+ Text("Prompts come at random times between these hours, spread through the day.")
+ }
+ } header: {
+ SettingsHeading(settings.weekendWindow == nil ? "Waking Hours" : "Weekdays")
+ }
+ if let weekend = settings.weekendWindow {
+ Section {
+ WindowPicker(
+ window: Binding(
+ get: { weekend },
+ set: { settings.weekendWindow = $0 }))
+ } header: {
+ SettingsHeading("Weekends")
+ }
+ }
+ Section {
+ Picker("Minimum Gap", selection: $settings.minimumGap) {
+ ForEach(Self.gaps, id: \.self) { minutes in
+ MinutesText(minutes: minutes).tag(minutes)
+ }
+ }
+ .settingsRow()
+ Picker("Snooze For", selection: $settings.snooze) {
+ ForEach(Self.snoozes, id: \.self) { minutes in
+ MinutesText(minutes: minutes).tag(minutes)
+ }
+ }
+ .settingsRow()
+ } header: {
+ SettingsHeading("Timing")
+ }
+ }
+ #if DEBUG
+ ScheduledPrompts(generation: scheduleGeneration)
+ #endif
+ }
+ .listStyle(.plain)
+ .scrollContentBackground(.hidden)
+ .background(Theme.paper)
+ .foregroundStyle(Theme.ink)
+ .navigationTitle("Notifications")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar(.visible, for: .navigationBar)
+ .task { await checkPermissions() }
+ .onChange(of: scenePhase) { _, phase in
+ if phase == .active { Task { await checkPermissions() } }
+ }
+ .onChange(of: settings) { _, settings in
+ settings.save()
+ Task {
+ await PromptScheduler().refresh()
+ scheduleGeneration += 1
+ }
+ }
+ }
+
+ @ViewBuilder
+ private var promptsFooter: some View {
+ if notifications == .denied {
+ VStack(alignment: .leading, spacing: Theme.lineGap) {
+ Text("Notifications are turned off for Reportage, so prompts can't be sent.")
+ if let url = URL(string: UIApplication.openNotificationSettingsURLString) {
+ Link("Open Settings", destination: url)
+ }
+ }
+ } else if settings.isEnabled, let location, location != .authorizedAlways {
+ VStack(alignment: .leading, spacing: Theme.lineGap) {
+ Text(
+ "Instant Report saves reports from a notification without a location unless location access for Reportage is set to Always."
+ )
+ if let url = URL(string: UIApplication.openSettingsURLString) {
+ Link("Open Settings", destination: url)
+ }
+ }
+ } else {
+ Text("Reportage sends a notification at random times each day, asking for a report.")
+ }
+ }
+
+ /// Turning prompts on asks for notifications (with the badge, which
+ /// counts instant reports) if they weren't allowed when the app was
+ /// first opened.
+ private var promptsEnabled: Binding<Bool> {
+ Binding(
+ get: { settings.isEnabled },
+ set: { isOn in
+ if isOn {
+ Task { await turnOnPrompts() }
+ } else {
+ settings.isEnabled = false
+ }
+ })
+ }
+
+ private var hasWeekendWindow: Binding<Bool> {
+ Binding(
+ get: { settings.weekendWindow != nil },
+ set: { settings.weekendWindow = $0 ? settings.window : nil })
+ }
+
+ private func turnOnPrompts() async {
+ let center = UNUserNotificationCenter.current()
+ let granted = (try? await center.requestAuthorization(options: [.alert, .sound, .badge])) ?? false
+ await checkPermissions()
+ guard granted else { return }
+ settings.isEnabled = true
+ await AppBadge.update(from: store)
+ }
+
+ private func checkPermissions() async {
+ notifications = await UNUserNotificationCenter.current().notificationSettings().authorizationStatus
+ location = CLLocationManager().authorizationStatus
+ }
+}
+
+/// The start and end of a waking window.
+private struct WindowPicker: View {
+ @Binding var window: WakingWindow
+
+ var body: some View {
+ DatePicker("From", selection: time(\.start), displayedComponents: .hourAndMinute)
+ .settingsRow()
+ DatePicker("Until", selection: time(\.end), displayedComponents: .hourAndMinute)
+ .settingsRow()
+ }
+
+ /// Minutes after midnight, as a time today for the picker.
+ private func time(_ keyPath: WritableKeyPath<WakingWindow, Int>) -> Binding<Date> {
+ Binding(
+ get: {
+ let minutes = window[keyPath: keyPath]
+ return Calendar.current.date(
+ bySettingHour: minutes / 60, minute: minutes % 60, second: 0, of: Date()) ?? Date()
+ },
+ set: { date in
+ let c = Calendar.current.dateComponents([.hour, .minute], from: date)
+ window[keyPath: keyPath] = (c.hour ?? 0) * 60 + (c.minute ?? 0)
+ })
+ }
+}
+
+#if DEBUG
+ /// The notifications waiting to be delivered, soonest first, to check
+ /// what the scheduler has done. Debug builds only.
+ private struct ScheduledPrompts: View {
+ let generation: Int
+
+ @State private var pending: [Pending] = []
+
+ private static let shown = 12
+
+ struct Pending: Identifiable {
+ let id: String
+ let date: Date?
+ }
+
+ var body: some View {
+ Section {
+ if pending.isEmpty {
+ SettingsNote { Text(verbatim: "Nothing scheduled.") }
+ }
+ ForEach(pending.prefix(Self.shown)) { item in
+ LabeledContent {
+ if let date = item.date {
+ Text(date, format: .dateTime.weekday(.abbreviated).hour().minute().second())
+ .monospacedDigit()
+ }
+ } label: {
+ Text(verbatim: item.id.split(separator: ".").first.map(String.init) ?? item.id)
+ }
+ .font(.footnote)
+ .settingsRow()
+ }
+ if pending.count > Self.shown {
+ SettingsNote { Text(verbatim: "and \(pending.count - Self.shown) more") }
+ }
+ } header: {
+ HStack {
+ SettingsHeading("Scheduled (\(pending.count))")
+ Button("Reload", systemImage: "arrow.clockwise") {
+ Task { await load() }
+ }
+ .labelStyle(.iconOnly)
+ .font(.footnote)
+ .padding(.trailing, Theme.margin)
+ }
+ .background(Theme.paper)
+ }
+ .task(id: generation) { await load() }
+ }
+
+ private func load() async {
+ let requests = await UNUserNotificationCenter.current().pendingNotificationRequests()
+ pending = requests
+ .map { request in
+ let date =
+ switch request.trigger {
+ case let trigger as UNCalendarNotificationTrigger: trigger.nextTriggerDate()
+ case let trigger as UNTimeIntervalNotificationTrigger: trigger.nextTriggerDate()
+ default: nil as Date?
+ }
+ return Pending(id: request.identifier, date: date)
+ }
+ .sorted { ($0.date ?? .distantFuture) < ($1.date ?? .distantFuture) }
+ }
+ }
+#endif
+
+/// A number of minutes, such as '30 min' or '1 hr, 30 min'.
+private struct MinutesText: View {
+ let minutes: Int
+
+ var body: some View {
+ if minutes == 0 {
+ Text("None", comment: "No minimum gap between prompts")
+ } else {
+ Text(
+ Duration.seconds(minutes * 60),
+ format: .units(allowed: [.hours, .minutes], width: .abbreviated))
+ }
+ }
+}
+
+#Preview {
+ NavigationStack {
+ NotificationsView()
+ }
+ .tint(Theme.accent)
+}
diff --git a/Reportage/Views/Settings/SettingsView.swift b/Reportage/Views/Settings/SettingsView.swift
@@ -1,24 +1,13 @@
-import CoreLocation
import SwiftUI
-import UserNotifications
-/// Settings: when random prompts come, and importing and exporting.
+/// Settings: the surveys, when random prompts come, and importing and
+/// exporting.
struct SettingsView: View {
- @Environment(\.reportStore) private var store
- @Environment(\.scenePhase) private var scenePhase
@State private var settings = PromptSettings.load()
- @State private var notifications: UNAuthorizationStatus?
- @State private var location: CLAuthorizationStatus?
- /// Counts finished reschedules, so the debug list of pending
- /// notifications reloads after each.
- @State private var scheduleGeneration = 0
#if DEBUG
@State private var isShowingWelcome = false
#endif
- private static let gaps = [0, 15, 30, 45, 60, 90, 120]
- private static let snoozes = [5, 10, 15, 20, 30, 60]
-
var body: some View {
NavigationStack {
List {
@@ -26,68 +15,25 @@ struct SettingsView: View {
Section {
NavigationLink("Questions") { QuestionsView() }
.settingsRow()
- } header: {
- SettingsHeading("Surveys")
- }
- Section {
- Toggle("Random Prompts", isOn: promptsEnabled)
- .settingsRow()
- if settings.isEnabled {
- Stepper(value: $settings.perDay, in: 1...12) {
- LabeledContent("Prompts a Day") {
- Text(settings.perDay, format: .number)
- .monospacedDigit()
+ NavigationLink {
+ NotificationsView()
+ } label: {
+ LabeledContent("Notifications") {
+ if settings.isEnabled {
+ Text("\(settings.perDay) a Day", comment: "How many random prompts come each day")
+ } else {
+ Text("Off", comment: "Random prompts are turned off")
}
}
- .settingsRow()
}
- SettingsNote { promptsFooter }
+ .settingsRow()
} header: {
- SettingsHeading("Prompts")
- }
- if settings.isEnabled {
- Section {
- WindowPicker(window: $settings.window)
- Toggle("Different Hours on Weekends", isOn: hasWeekendWindow)
- .settingsRow()
- SettingsNote {
- Text("Prompts come at random times between these hours, spread through the day.")
- }
- } header: {
- SettingsHeading(settings.weekendWindow == nil ? "Waking Hours" : "Weekdays")
- }
- if let weekend = settings.weekendWindow {
- Section {
- WindowPicker(
- window: Binding(
- get: { weekend },
- set: { settings.weekendWindow = $0 }))
- } header: {
- SettingsHeading("Weekends")
- }
- }
- Section {
- Picker("Minimum Gap", selection: $settings.minimumGap) {
- ForEach(Self.gaps, id: \.self) { minutes in
- MinutesText(minutes: minutes).tag(minutes)
- }
- }
- .settingsRow()
- Picker("Snooze For", selection: $settings.snooze) {
- ForEach(Self.snoozes, id: \.self) { minutes in
- MinutesText(minutes: minutes).tag(minutes)
- }
- }
- .settingsRow()
- } header: {
- SettingsHeading("Timing")
- }
+ SettingsHeading("Surveys")
}
DataSection()
DiagnosticsSection()
#if DEBUG
WelcomeReplay { isShowingWelcome = true }
- ScheduledPrompts(generation: scheduleGeneration)
#endif
}
.listStyle(.plain)
@@ -98,110 +44,14 @@ struct SettingsView: View {
}
#if DEBUG
// On the screen rather than the row: a cover attached inside
- // the list is dismissed when the list rebuilds the row, as it
- // does while the scheduled prompts load.
+ // the list is dismissed when the list rebuilds the row.
.fullScreenCover(isPresented: $isShowingWelcome) {
WelcomeView { isShowingWelcome = false }
}
#endif
- .task { await checkPermissions() }
- .onChange(of: scenePhase) { _, phase in
- if phase == .active { Task { await checkPermissions() } }
- }
// Prompts may have been turned on when the app was first opened,
- // after this view was made.
+ // after this view was made, or changed on the Notifications screen.
.onAppear { settings = PromptSettings.load() }
- .onChange(of: settings) { _, settings in
- settings.save()
- Task {
- await PromptScheduler().refresh()
- scheduleGeneration += 1
- }
- }
- }
-
- @ViewBuilder
- private var promptsFooter: some View {
- if notifications == .denied {
- VStack(alignment: .leading, spacing: Theme.lineGap) {
- Text("Notifications are turned off for Reportage, so prompts can't be sent.")
- if let url = URL(string: UIApplication.openNotificationSettingsURLString) {
- Link("Open Settings", destination: url)
- }
- }
- } else if settings.isEnabled, let location, location != .authorizedAlways {
- VStack(alignment: .leading, spacing: Theme.lineGap) {
- Text(
- "Instant Report saves reports from a notification without a location unless location access for Reportage is set to Always."
- )
- if let url = URL(string: UIApplication.openSettingsURLString) {
- Link("Open Settings", destination: url)
- }
- }
- } else {
- Text("Reportage sends a notification at random times each day, asking for a report.")
- }
- }
-
- /// Turning prompts on asks for notifications (with the badge, which
- /// counts instant reports) if they weren't allowed when the app was
- /// first opened.
- private var promptsEnabled: Binding<Bool> {
- Binding(
- get: { settings.isEnabled },
- set: { isOn in
- if isOn {
- Task { await turnOnPrompts() }
- } else {
- settings.isEnabled = false
- }
- })
- }
-
- private var hasWeekendWindow: Binding<Bool> {
- Binding(
- get: { settings.weekendWindow != nil },
- set: { settings.weekendWindow = $0 ? settings.window : nil })
- }
-
- private func turnOnPrompts() async {
- let center = UNUserNotificationCenter.current()
- let granted = (try? await center.requestAuthorization(options: [.alert, .sound, .badge])) ?? false
- await checkPermissions()
- guard granted else { return }
- settings.isEnabled = true
- await AppBadge.update(from: store)
- }
-
- private func checkPermissions() async {
- notifications = await UNUserNotificationCenter.current().notificationSettings().authorizationStatus
- location = CLLocationManager().authorizationStatus
- }
-}
-
-/// The start and end of a waking window.
-private struct WindowPicker: View {
- @Binding var window: WakingWindow
-
- var body: some View {
- DatePicker("From", selection: time(\.start), displayedComponents: .hourAndMinute)
- .settingsRow()
- DatePicker("Until", selection: time(\.end), displayedComponents: .hourAndMinute)
- .settingsRow()
- }
-
- /// Minutes after midnight, as a time today for the picker.
- private func time(_ keyPath: WritableKeyPath<WakingWindow, Int>) -> Binding<Date> {
- Binding(
- get: {
- let minutes = window[keyPath: keyPath]
- return Calendar.current.date(
- bySettingHour: minutes / 60, minute: minutes % 60, second: 0, of: Date()) ?? Date()
- },
- set: { date in
- let c = Calendar.current.dateComponents([.hour, .minute], from: date)
- window[keyPath: keyPath] = (c.hour ?? 0) * 60 + (c.minute ?? 0)
- })
}
}
@@ -282,88 +132,8 @@ extension View {
}
}
}
-
- /// The notifications waiting to be delivered, soonest first, to check
- /// what the scheduler has done. Debug builds only.
- private struct ScheduledPrompts: View {
- let generation: Int
-
- @State private var pending: [Pending] = []
-
- private static let shown = 12
-
- struct Pending: Identifiable {
- let id: String
- let date: Date?
- }
-
- var body: some View {
- Section {
- if pending.isEmpty {
- SettingsNote { Text(verbatim: "Nothing scheduled.") }
- }
- ForEach(pending.prefix(Self.shown)) { item in
- LabeledContent {
- if let date = item.date {
- Text(date, format: .dateTime.weekday(.abbreviated).hour().minute().second())
- .monospacedDigit()
- }
- } label: {
- Text(verbatim: item.id.split(separator: ".").first.map(String.init) ?? item.id)
- }
- .font(.footnote)
- .settingsRow()
- }
- if pending.count > Self.shown {
- SettingsNote { Text(verbatim: "and \(pending.count - Self.shown) more") }
- }
- } header: {
- HStack {
- SettingsHeading("Scheduled (\(pending.count))")
- Button("Reload", systemImage: "arrow.clockwise") {
- Task { await load() }
- }
- .labelStyle(.iconOnly)
- .font(.footnote)
- .padding(.trailing, Theme.margin)
- }
- .background(Theme.paper)
- }
- .task(id: generation) { await load() }
- }
-
- private func load() async {
- let requests = await UNUserNotificationCenter.current().pendingNotificationRequests()
- pending = requests
- .map { request in
- let date =
- switch request.trigger {
- case let trigger as UNCalendarNotificationTrigger: trigger.nextTriggerDate()
- case let trigger as UNTimeIntervalNotificationTrigger: trigger.nextTriggerDate()
- default: nil as Date?
- }
- return Pending(id: request.identifier, date: date)
- }
- .sorted { ($0.date ?? .distantFuture) < ($1.date ?? .distantFuture) }
- }
- }
#endif
-/// A number of minutes, such as '30 min' or '1 hr, 30 min'.
-private struct MinutesText: View {
- let minutes: Int
-
- var body: some View {
- if minutes == 0 {
- Text("None", comment: "No minimum gap between prompts")
- } else {
- Text(
- Duration.seconds(minutes * 60),
- format: .units(allowed: [.hours, .minutes], width: .abbreviated))
- }
- }
-}
-
#Preview {
SettingsView()
.tint(Theme.accent)