← All repositories

reportage

A life-logging app for iPhone

git clone https://code.inqk.net/reportage.git


Reportage/Views/Settings/NotificationsView.swift (10413B)

1import CoreLocation
2import SwiftUI
3import UserNotifications
4
5/// When random prompts come: how many, between which hours and how far
6/// apart.
7struct NotificationsView: View {
8    @Environment(\.scenePhase) private var scenePhase
9    @State private var settings = PromptSettings.load()
10    @State private var notifications: UNAuthorizationStatus?
11    @State private var location: CLAuthorizationStatus?
12    /// Counts finished reschedules, so the debug list of pending
13    /// notifications reloads after each.
14    @State private var scheduleGeneration = 0
15
16    private static let gaps = [0, 15, 30, 45, 60, 90, 120]
17    private static let snoozes = [5, 10, 15, 20, 30, 60]
18
19    var body: some View {
20        List {
21            Section {
22                Toggle("Random Prompts", isOn: promptsEnabled)
23                    .settingsRow()
24                    .listRowSeparator(.hidden, edges: .top)
25                if settings.isEnabled {
26                    Stepper(value: $settings.perDay, in: 1...12) {
27                        LabeledContent("Prompts a Day") {
28                            Text(settings.perDay, format: .number)
29                                .monospacedDigit()
30                        }
31                    }
32                    .settingsRow()
33                }
34                SettingsNote { promptsFooter }
35            }
36            if settings.isEnabled {
37                Section {
38                    WindowPicker(window: $settings.window)
39                    Toggle("Different Hours on Weekends", isOn: hasWeekendWindow)
40                        .settingsRow()
41                    SettingsNote {
42                        Text("Prompts come at random times between these hours, spread through the day.")
43                    }
44                } header: {
45                    SettingsHeading(settings.weekendWindow == nil ? "Waking Hours" : "Weekdays")
46                }
47                if let weekend = settings.weekendWindow {
48                    Section {
49                        WindowPicker(
50                            window: Binding(
51                                get: { weekend },
52                                set: { settings.weekendWindow = $0 }))
53                    } header: {
54                        SettingsHeading("Weekends")
55                    }
56                }
57                Section {
58                    Picker("Minimum Gap", selection: $settings.minimumGap) {
59                        ForEach(Self.gaps, id: \.self) { minutes in
60                            MinutesText(minutes: minutes).tag(minutes)
61                        }
62                    }
63                    .settingsRow()
64                    Picker("Snooze For", selection: $settings.snooze) {
65                        ForEach(Self.snoozes, id: \.self) { minutes in
66                            MinutesText(minutes: minutes).tag(minutes)
67                        }
68                    }
69                    .settingsRow()
70                } header: {
71                    SettingsHeading("Timing")
72                }
73            }
74            #if DEBUG
75                ScheduledPrompts(generation: scheduleGeneration)
76            #endif
77        }
78        .listStyle(.plain)
79        .scrollContentBackground(.hidden)
80        .tabBarClearance()
81        .background(Theme.paper)
82        .foregroundStyle(Theme.ink)
83        .navigationTitle("Notifications")
84        .navigationBarTitleDisplayMode(.inline)
85        .toolbar(.visible, for: .navigationBar)
86        .task { await checkPermissions() }
87        .onChange(of: scenePhase) { _, phase in
88            if phase == .active { Task { await checkPermissions() } }
89        }
90        .onChange(of: settings) { _, settings in
91            settings.save()
92            Task {
93                await PromptScheduler().refresh()
94                scheduleGeneration += 1
95            }
96        }
97    }
98
99    @ViewBuilder
100    private var promptsFooter: some View {
101        if notifications == .denied {
102            VStack(alignment: .leading, spacing: Theme.lineGap) {
103                Text("Notifications are turned off for Reportage, so prompts can't be sent.")
104                if let url = URL(string: UIApplication.openNotificationSettingsURLString) {
105                    Link("Open Settings", destination: url)
106                }
107            }
108        } else if settings.isEnabled, let location, location != .authorizedAlways {
109            VStack(alignment: .leading, spacing: Theme.lineGap) {
110                Text(
111                    "Instant Report saves reports from a notification without a location unless location access for Reportage is set to Always."
112                )
113                if let url = URL(string: UIApplication.openSettingsURLString) {
114                    Link("Open Settings", destination: url)
115                }
116            }
117        } else {
118            Text("Reportage sends a notification at random times each day, asking for a report.")
119        }
120    }
121
122    /// Turning prompts on asks for notifications if they weren't allowed
123    /// when the app was first opened.
124    private var promptsEnabled: Binding<Bool> {
125        Binding(
126            get: { settings.isEnabled },
127            set: { isOn in
128                if isOn {
129                    Task { await turnOnPrompts() }
130                } else {
131                    settings.isEnabled = false
132                }
133            })
134    }
135
136    private var hasWeekendWindow: Binding<Bool> {
137        Binding(
138            get: { settings.weekendWindow != nil },
139            set: { settings.weekendWindow = $0 ? settings.window : nil })
140    }
141
142    private func turnOnPrompts() async {
143        let center = UNUserNotificationCenter.current()
144        let granted = (try? await center.requestAuthorization(options: [.alert, .sound])) ?? false
145        await checkPermissions()
146        guard granted else { return }
147        settings.isEnabled = true
148    }
149
150    private func checkPermissions() async {
151        notifications = await UNUserNotificationCenter.current().notificationSettings().authorizationStatus
152        location = CLLocationManager().authorizationStatus
153    }
154}
155
156/// The start and end of a waking window.
157private struct WindowPicker: View {
158    @Binding var window: WakingWindow
159
160    var body: some View {
161        DatePicker("From", selection: time(\.start), displayedComponents: .hourAndMinute)
162            .settingsRow()
163        DatePicker("Until", selection: time(\.end), displayedComponents: .hourAndMinute)
164            .settingsRow()
165    }
166
167    /// Minutes after midnight, as a time today for the picker.
168    private func time(_ keyPath: WritableKeyPath<WakingWindow, Int>) -> Binding<Date> {
169        Binding(
170            get: {
171                let minutes = window[keyPath: keyPath]
172                return Calendar.current.date(
173                    bySettingHour: minutes / 60, minute: minutes % 60, second: 0, of: Date()) ?? Date()
174            },
175            set: { date in
176                let c = Calendar.current.dateComponents([.hour, .minute], from: date)
177                window[keyPath: keyPath] = (c.hour ?? 0) * 60 + (c.minute ?? 0)
178            })
179    }
180}
181
182#if DEBUG
183    /// The notifications waiting to be delivered, soonest first, to check
184    /// what the scheduler has done. Debug builds only.
185    private struct ScheduledPrompts: View {
186        let generation: Int
187
188        @State private var pending: [Pending] = []
189
190        private static let shown = 12
191
192        struct Pending: Identifiable {
193            let id: String
194            let date: Date?
195        }
196
197        var body: some View {
198            Section {
199                if pending.isEmpty {
200                    SettingsNote { Text(verbatim: "Nothing scheduled.") }
201                }
202                ForEach(pending.prefix(Self.shown)) { item in
203                    LabeledContent {
204                        if let date = item.date {
205                            Text(date, format: .dateTime.weekday(.abbreviated).hour().minute().second())
206                                .monospacedDigit()
207                        }
208                    } label: {
209                        Text(verbatim: item.id.split(separator: ".").first.map(String.init) ?? item.id)
210                    }
211                    .font(.footnote)
212                    .settingsRow()
213                }
214                if pending.count > Self.shown {
215                    SettingsNote { Text(verbatim: "and \(pending.count - Self.shown) more") }
216                }
217            } header: {
218                HStack {
219                    SettingsHeading("Scheduled (\(pending.count))")
220                    Button("Reload", systemImage: "arrow.clockwise") {
221                        Task { await load() }
222                    }
223                    .labelStyle(.iconOnly)
224                    .font(.footnote)
225                    .padding(.trailing, Theme.margin)
226                }
227                .background(Theme.paper)
228                // The list takes a header's insets from its outermost view,
229                // so the heading's own zero insets don't reach it here.
230                .listRowInsets(EdgeInsets())
231            }
232            .task(id: generation) { await load() }
233        }
234
235        private func load() async {
236            let requests = await UNUserNotificationCenter.current().pendingNotificationRequests()
237            pending = requests
238                .map { request in
239                    let date =
240                        switch request.trigger {
241                        case let trigger as UNCalendarNotificationTrigger: trigger.nextTriggerDate()
242                        case let trigger as UNTimeIntervalNotificationTrigger: trigger.nextTriggerDate()
243                        default: nil as Date?
244                        }
245                    return Pending(id: request.identifier, date: date)
246                }
247                .sorted { ($0.date ?? .distantFuture) < ($1.date ?? .distantFuture) }
248        }
249    }
250#endif
251
252/// A number of minutes, such as '30 min' or '1 hr, 30 min'.
253private struct MinutesText: View {
254    let minutes: Int
255
256    var body: some View {
257        if minutes == 0 {
258            Text("None", comment: "No minimum gap between prompts")
259        } else {
260            Text(
261                Duration.seconds(minutes * 60),
262                format: .units(allowed: [.hours, .minutes], width: .abbreviated))
263        }
264    }
265}
266
267#Preview {
268    NavigationStack {
269        NotificationsView()
270    }
271    .tint(Theme.accent)
272}