Reportage/AppDelegate.swift (3989B)
1import AppIntents
2import BackgroundTasks
3import SwiftUI
4import UserNotifications
5
6
7
8final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
9
10
11 let persistence = PersistenceController(inMemory: DemoSeed.isActive)
12 let inbox = PromptInbox()
13 lazy var healthFiller = HealthFiller(store: ReportStore(persistence: persistence))
14 lazy var addressUpdater = AddressUpdater(store: ReportStore(persistence: persistence))
15
16 let backgroundLocation = BackgroundLocation()
17
18 private let log = EventLog.shared.category("Prompts")
19
20
21
22 override init() {
23 super.init()
24 let persistence = persistence
25 AppDependencyManager.shared.add(dependency: InstantReportLogger(persistence: persistence) as any InstantReportLogging)
26 }
27
28 func application(
29 _ application: UIApplication,
30 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
31 ) -> Bool {
32
33
34 let state = application.applicationState == .background ? "in the background" : "in the foreground"
35 EventLog.shared.note("Launched \(state)", category: "App")
36 let center = UNUserNotificationCenter.current()
37 center.delegate = self
38 center.setNotificationCategories(PromptNotification.categories)
39 return true
40 }
41
42
43 nonisolated func userNotificationCenter(
44 _ center: UNUserNotificationCenter, willPresent notification: UNNotification
45 ) async -> UNNotificationPresentationOptions {
46 [.banner, .list, .sound]
47 }
48
49 nonisolated func userNotificationCenter(
50 _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse
51 ) async {
52 await handle(PromptResponse(response))
53 }
54
55 private func handle(_ response: PromptResponse) async {
56 let store = ReportStore(persistence: persistence)
57 let state = UIApplication.shared.applicationState == .background ? "in the background" : "in the foreground"
58 log.info("Received '\(response.action)' for a '\(response.category)' notification, \(state)")
59 do {
60 let survey = try await PromptResponder(store: store)
61 .respond(to: response, settings: .load())
62 if let survey {
63 inbox.survey = survey
64 }
65 log.info("Handled '\(response.action)'")
66 } catch {
67 log.error("Couldn't respond to a prompt: \(error)")
68 }
69
70 await PromptScheduler().refresh()
71 }
72}
73
74
75
76@MainActor
77@Observable
78final class PromptInbox {
79 var survey: SurveyRequest?
80
81
82 func take() -> SurveyRequest? {
83 defer { survey = nil }
84 return survey
85 }
86}
87
88
89
90enum BackgroundRefresh {
91 static let identifier = "net.inqk.reportage.prompts"
92
93
94
95 static func submit() {
96 let request = BGAppRefreshTaskRequest(identifier: identifier)
97 request.earliestBeginDate = Date(timeIntervalSinceNow: 6 * 60 * 60)
98 try? BGTaskScheduler.shared.submit(request)
99 }
100}