← All repositories

reportage

A life-logging app for iPhone

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


Reportage/AppDelegate.swift (3989B)

1import AppIntents
2import BackgroundTasks
3import SwiftUI
4import UserNotifications
5
6/// Owns the store, and handles notifications: the notification delegate has
7/// to be set before launch finishes, or a tap that launched the app is lost.
8final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
9    /// In memory for the demo, so its invented reports never reach the real
10    /// store.
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    /// Made with the delegate, as early in launch as there is.
16    let backgroundLocation = BackgroundLocation()
17
18    private let log = EventLog.shared.category("Prompts")
19
20    /// Registers what App Intents need here, because the system can launch
21    /// the app in the background just to perform an intent.
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        // Says whether the app was opened or launched unseen, as it is for a
33        // notification action.
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    /// Prompts arriving while the app is open are shown as usual.
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        // An action is a chance to top up the prompts.
70        await PromptScheduler().refresh()
71    }
72}
73
74/// The survey a tapped prompt asks for, held until the home screen can
75/// show it.
76@MainActor
77@Observable
78final class PromptInbox {
79    var survey: SurveyRequest?
80
81    /// Takes the waiting survey, if there is one.
82    func take() -> SurveyRequest? {
83        defer { survey = nil }
84        return survey
85    }
86}
87
88/// Background refresh tops up the prompts when the app hasn't been opened
89/// for a while.
90enum BackgroundRefresh {
91    static let identifier = "net.inqk.reportage.prompts"
92
93    /// Asks for the next refresh. Only one request is kept, so asking again
94    /// replaces it.
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}