commit 4e56507484053bb87baf49359fc7413168e4b820
parent 365f2f2a066dd500858641053d5f8ac4fe7dd9e5
Author: Michael Camilleri <[email protected]>
Date: Thu, 22 Oct 2026 00:01:01 +0900
Add an optional App Lock using Face ID
Reportage holds a personal life log, but anyone holding the unlocked
iPhone could open it and read every report.
This commit adds App Lock to the Miscellaneous section of Settings. When
it's on, the app asks for Face ID, or the device passcode when Face ID
fails or isn't set up, either immediately on returning or after 1, 5 or
15 minutes in the background. Turning the lock on or off asks for Face
ID first. Only a return from the background locks the app, since Face
ID's own prompt and Control Center make it inactive without leaving it.
While the app is locked, or in the background with the lock on, a
window above everything else covers it, so the app switcher's snapshot
shows nothing and a survey opened from a prompt waits beneath it until
the app is unlocked. Notification actions, Instant Reports and Shortcuts
show nothing, so they still work while locked. The setting is per device
and isn't synced or exported.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat
| M | Notes/Design.md | | | 24 | ++++++++++++++++++++---- |
| M | Reportage.xcodeproj/project.pbxproj | | | 16 | ++++++++++++++++ |
| M | Reportage/Info.plist | | | 2 | ++ |
| M | Reportage/ReportageApp.swift | | | 8 | +++++++- |
| A | Reportage/Services/AppLock.swift | | | 210 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | Reportage/Views/LockView.swift | | | 34 | ++++++++++++++++++++++++++++++++++ |
| A | Reportage/Views/Settings/AppLockView.swift | | | 70 | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| M | Reportage/Views/Settings/SettingsView.swift | | | 16 | ++++++++++++++++ |
| A | Tests/Unit/AppLockTests.swift | | | 119 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| M | project.yml | | | 1 | + |
10 files changed, 495 insertions(+), 5 deletions(-)
diff --git a/Notes/Design.md b/Notes/Design.md
@@ -480,7 +480,8 @@ Chinese, Japanese or Korean script, which put the family name first and are shown whole. Places read as below. A token's `narrativeForm`, when set, wins over all of these. -Narratives are English only for now. +Narratives are English only; other languages aren't planned. A name in +another script can be given an English narrative form. ### Places @@ -814,6 +815,22 @@ Health grows. Battery from `UIDevice`, connectivity from `NWPathMonitor`. +## App Lock + +**Settings → App Lock** can lock the app behind Face ID, falling back to the +device passcode. It's off by default, and turning it on or off asks for Face +ID first. The lock comes back immediately on leaving the app, or after 1, 5 +or 15 minutes in the background. Only a return from the background locks: +Face ID's own prompt and Control Center make the app inactive without +leaving it. + +While the app is locked, or in the background with the lock on, a window +above everything else covers it, so the app switcher's snapshot shows +nothing. A survey opened by tapping a prompt waits beneath it until the app +is unlocked. Notification actions, Instant Reports and Shortcuts show +nothing, so they work while locked. The setting is per device and isn't +synced or exported. + ## Sync Private CloudKit database via `CKSyncEngine`, with two custom zones: @@ -1085,6 +1102,5 @@ the locale uses for weather. Sleep isn't charted. is worked on later. - **Multi-select choice questions.** Reporter stores choice answers as arrays, but every answer in the archive has a single value. The survey takes one - answer for now. -- **Narratives in other languages.** Narratives are English only. -- **App lock.** Should there be an optional Face ID lock? The data is personal. + answer for now. Deferred: choice answers are already stored as lists, so + this needs no format change.
diff --git a/Reportage.xcodeproj/project.pbxproj b/Reportage.xcodeproj/project.pbxproj
@@ -12,8 +12,10 @@
06415D2A2EDA6E92ECAC96FA /* Report.swift in Sources */ = {isa = PBXBuildFile; fileRef = B03734F91822E7F161432075 /* Report.swift */; };
06BD386D5CA144F8D5053A39 /* NotificationsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F832E0B277D5BF5BC3B6E5D1 /* NotificationsView.swift */; };
0AFAC8D04793CD85CFEE7329 /* ArchiveFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7117B46D7B8EE8E2510F806D /* ArchiveFormat.swift */; };
+ 0BF3E99963E608CAEF35A8C2 /* AppLockView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9C6B56A4E7C9BDB507251E38 /* AppLockView.swift */; };
0F052B8A2C73437F57E927E7 /* ReportStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84E55C093BA98D8700F406AE /* ReportStoreTests.swift */; };
123470F9E3205890526D3A89 /* EventLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = BFF717BC324925C231BD3378 /* EventLog.swift */; };
+ 134F7AA5B77AD43ADE447997 /* AppLockTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 88E99EFC0220DB7FDC5B0304 /* AppLockTests.swift */; };
141F97BD7B695424E7ED30D6 /* ContextCharts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 996F5818A958E305371F4BE3 /* ContextCharts.swift */; };
16CDDFE25EBB07C0EA9AC5AA /* DiagnosticsSection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 87545A7909A370C668314DFF /* DiagnosticsSection.swift */; };
16D2FB106A2C588BAAB3EB06 /* PromptSchedulerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2425CB4D9B12D422467F6FD7 /* PromptSchedulerTests.swift */; };
@@ -83,6 +85,7 @@
B4669F1DB73592E4770A91FC /* AddressFillTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 056384B5C80E683A6A9440C0 /* AddressFillTests.swift */; };
B510BB2C1C11D72DFE15E3C7 /* ReportageExportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DB6FF151DCEBC3913131834 /* ReportageExportTests.swift */; };
B5642835F1FD86CA4AE39408 /* ContextSummary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0950575E9B01E6885B1BDA09 /* ContextSummary.swift */; };
+ B8BAFB88F8AE9E36EABF5399 /* LockView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B91790E0C0C28BAC1F17DF0 /* LockView.swift */; };
BD1AA0F75635BF9C68DFA12A /* NarrativeRule.swift in Sources */ = {isa = PBXBuildFile; fileRef = E67FAC24A684AA62ED63441A /* NarrativeRule.swift */; };
BD8D81CBF8C3DE544BB7540C /* DefaultQuestions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 94DB0CA378AEF82B3CB27B67 /* DefaultQuestions.swift */; };
BDEB83CDBA9E0B4DB7712491 /* LogPassiveReportIntent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 90F9BD4EA70DCB46924CF9B8 /* LogPassiveReportIntent.swift */; };
@@ -92,6 +95,7 @@
C87E1C0465FE7B2917F92846 /* PromptSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = DB87A3E922FA7AE98B93DF1E /* PromptSettings.swift */; };
C8E02DEA2119E61D31667FFE /* ReporterImportPlanTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FD562C0C92C1D59881C771E /* ReporterImportPlanTests.swift */; };
C9FD2FE13F80F1F064A0DEC2 /* ReportageImporter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83C5FB4631405F1706BB2C94 /* ReportageImporter.swift */; };
+ CA0ED469884532E6B55E8687 /* AppLock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4268FD633DD38718BE4D51F8 /* AppLock.swift */; };
CFB0A1F9494F1D8919F48CC5 /* ContextCaptureTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A3157F7D5E4289B349E92402 /* ContextCaptureTests.swift */; };
D1F2257DDB68439AF352B57D /* PassiveLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46FB42E5DB43201A13D6D141 /* PassiveLog.swift */; };
D1FFB84FFDF0F659D8D78AEB /* ReportageWidgets.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7EDD39E85D86AFF45B5672F3 /* ReportageWidgets.swift */; };
@@ -177,6 +181,7 @@
3DF3B490F336FCE1E1E3DDBA /* RealExportVerificationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RealExportVerificationTests.swift; sourceTree = "<group>"; };
3ED0CAE575381DCB86FB8EE9 /* ReporterImportVerifier.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterImportVerifier.swift; sourceTree = "<group>"; };
3F0E3407B3FF5616EE56428B /* AddressFill.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AddressFill.swift; sourceTree = "<group>"; };
+ 4268FD633DD38718BE4D51F8 /* AppLock.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppLock.swift; sourceTree = "<group>"; };
46FB42E5DB43201A13D6D141 /* PassiveLog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PassiveLog.swift; sourceTree = "<group>"; };
487F88C880B5DE69964C6A37 /* ReporterArchiveTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterArchiveTests.swift; sourceTree = "<group>"; };
48ACB0E76C4E2271EA59B8E9 /* QuestionEditorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QuestionEditorTests.swift; sourceTree = "<group>"; };
@@ -204,6 +209,7 @@
76FFC5FE874467974DD6BFA0 /* PlaceRanking.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlaceRanking.swift; sourceTree = "<group>"; };
798E1DE82BD53EC5BEBA76B7 /* ReporterImportPlan.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterImportPlan.swift; sourceTree = "<group>"; };
7ABE75DB46245AFDE8A44A48 /* Config.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Config.xcconfig; sourceTree = "<group>"; };
+ 7B91790E0C0C28BAC1F17DF0 /* LockView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LockView.swift; sourceTree = "<group>"; };
7CE9EDC8448889EB9D4D358E /* FirstLaunch.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirstLaunch.swift; sourceTree = "<group>"; };
7DB6FF151DCEBC3913131834 /* ReportageExportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportageExportTests.swift; sourceTree = "<group>"; };
7EDD39E85D86AFF45B5672F3 /* ReportageWidgets.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportageWidgets.swift; sourceTree = "<group>"; };
@@ -218,12 +224,14 @@
86474CD2E8EC300CD6B37BB2 /* PromptSchedule.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PromptSchedule.swift; sourceTree = "<group>"; };
87545A7909A370C668314DFF /* DiagnosticsSection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiagnosticsSection.swift; sourceTree = "<group>"; };
878CE0FF7A2598F4197E8E61 /* Environment.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Environment.swift; sourceTree = "<group>"; };
+ 88E99EFC0220DB7FDC5B0304 /* AppLockTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppLockTests.swift; sourceTree = "<group>"; };
90F9BD4EA70DCB46924CF9B8 /* LogPassiveReportIntent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LogPassiveReportIntent.swift; sourceTree = "<group>"; };
917C4579342FAC42F6C616FC /* ReporterImporterTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterImporterTests.swift; sourceTree = "<group>"; };
92BFA1E8F26662DCF828DD5C /* WelcomeView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WelcomeView.swift; sourceTree = "<group>"; };
94DB0CA378AEF82B3CB27B67 /* DefaultQuestions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DefaultQuestions.swift; sourceTree = "<group>"; };
9856D1F8123B9CAD7D39071D /* PlaceAnswerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlaceAnswerView.swift; sourceTree = "<group>"; };
996F5818A958E305371F4BE3 /* ContextCharts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContextCharts.swift; sourceTree = "<group>"; };
+ 9C6B56A4E7C9BDB507251E38 /* AppLockView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppLockView.swift; sourceTree = "<group>"; };
9F3237323A968FA629020DA9 /* ContextCapture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContextCapture.swift; sourceTree = "<group>"; };
A00E589A8387E7A1E348503C /* InlineCasing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InlineCasing.swift; sourceTree = "<group>"; };
A20C574BC234EDBD4056E2B7 /* TestHelpers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TestHelpers.swift; sourceTree = "<group>"; };
@@ -422,6 +430,7 @@
60B58F5030E4A690025C51F5 /* Services */ = {
isa = PBXGroup;
children = (
+ 4268FD633DD38718BE4D51F8 /* AppLock.swift */,
EC0EF3DA62941ED76148D5BF /* BackgroundLocation.swift */,
0A04A07EB408F4DA589B65AB /* DemoSeed.swift */,
7CE9EDC8448889EB9D4D358E /* FirstLaunch.swift */,
@@ -472,6 +481,7 @@
children = (
056384B5C80E683A6A9440C0 /* AddressFillTests.swift */,
3A4B10FFBEDE5D6E23B1B2B4 /* AnswerSummaryTests.swift */,
+ 88E99EFC0220DB7FDC5B0304 /* AppLockTests.swift */,
A3157F7D5E4289B349E92402 /* ContextCaptureTests.swift */,
A7DD8E44D1A1F7789F528BD3 /* EventLogTests.swift */,
695CB01E79016592A3823541 /* HealthTests.swift */,
@@ -545,6 +555,7 @@
isa = PBXGroup;
children = (
1AD7CB7E9FF6D01BF4CE8617 /* AboutView.swift */,
+ 9C6B56A4E7C9BDB507251E38 /* AppLockView.swift */,
CA2E66BAB2463FD51EFE9F52 /* DataSection.swift */,
87545A7909A370C668314DFF /* DiagnosticsSection.swift */,
0EC45BA4E4F82AC5DC8FBDE2 /* HistoricalDataView.swift */,
@@ -574,6 +585,7 @@
isa = PBXGroup;
children = (
878CE0FF7A2598F4197E8E61 /* Environment.swift */,
+ 7B91790E0C0C28BAC1F17DF0 /* LockView.swift */,
5591E042089D038B59B26E9F /* ReportKind+Title.swift */,
A70B6E5B7C07D2CE13E9E771 /* RootView.swift */,
92BFA1E8F26662DCF828DD5C /* WelcomeView.swift */,
@@ -754,6 +766,7 @@
files = (
B4669F1DB73592E4770A91FC /* AddressFillTests.swift in Sources */,
696B8F7586F680B1F5C41382 /* AnswerSummaryTests.swift in Sources */,
+ 134F7AA5B77AD43ADE447997 /* AppLockTests.swift in Sources */,
CFB0A1F9494F1D8919F48CC5 /* ContextCaptureTests.swift in Sources */,
A7C988B20CD1C937A2E776D0 /* EventLogTests.swift in Sources */,
905D1185CF8B3426ECB91AFD /* HealthTests.swift in Sources */,
@@ -788,6 +801,8 @@
D3710CE243BC4BB46C12B8FE /* AddressFill.swift in Sources */,
E3C74ABCE348FFF05890690E /* AnswerSummary.swift in Sources */,
B454D3067CD611AE55E30A1D /* AppDelegate.swift in Sources */,
+ CA0ED469884532E6B55E8687 /* AppLock.swift in Sources */,
+ 0BF3E99963E608CAEF35A8C2 /* AppLockView.swift in Sources */,
E8C13757BF3E2C8384F104A1 /* AppleWeather.swift in Sources */,
0AFAC8D04793CD85CFEE7329 /* ArchiveFormat.swift in Sources */,
811704907EE199CC627F0CE5 /* BackgroundLocation.swift in Sources */,
@@ -813,6 +828,7 @@
6E21E729F89178EBD019980E /* InlineCasing.swift in Sources */,
275A9497C40065F5C77AE473 /* InstantReportLogger.swift in Sources */,
3244B8439B5E4F79FF84C156 /* JSONSlicer.swift in Sources */,
+ B8BAFB88F8AE9E36EABF5399 /* LockView.swift in Sources */,
BDEB83CDBA9E0B4DB7712491 /* LogPassiveReportIntent.swift in Sources */,
9DFFA4F1FE8F9201855D5884 /* NarrativeBuilder.swift in Sources */,
BD1AA0F75635BF9C68DFA12A /* NarrativeRule.swift in Sources */,
diff --git a/Reportage/Info.plist b/Reportage/Info.plist
@@ -39,6 +39,8 @@ <false/> <key>LSRequiresIPhoneOS</key> <true/> + <key>NSFaceIDUsageDescription</key> + <string>Reportage uses Face ID to unlock the app when App Lock is turned on.</string> <key>NSHealthShareUsageDescription</key> <string>Reportage records your steps and other activity so far that day with each report, and how you slept with wake reports. Health data stays on this iPhone.</string> <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
diff --git a/Reportage/ReportageApp.swift b/Reportage/ReportageApp.swift
@@ -5,6 +5,7 @@ import SwiftUI
struct ReportageApp: App {
@UIApplicationDelegateAdaptor private var appDelegate: AppDelegate
@Environment(\.scenePhase) private var scenePhase
+ @State private var appLock = AppLock()
private let logger = Logger(subsystem: "net.inqk.reportage", category: "App")
@@ -16,21 +17,26 @@ struct ReportageApp: App {
.environment(appDelegate.inbox)
.environment(appDelegate.healthFiller)
.environment(appDelegate.addressUpdater)
+ .environment(appLock)
.tint(Theme.accent)
.task { await prepareQuestions() }
}
.onChange(of: scenePhase) { _, phase in
switch phase {
case .active:
+ appLock.didBecomeActive()
Task { await PromptScheduler().refresh() }
appDelegate.backgroundLocation.refresh(renewing: true)
// Health can only be read while the iPhone is unlocked.
appDelegate.healthFiller.fillRecent()
+ case .inactive:
+ appLock.didBecomeInactive()
case .background:
+ appLock.didEnterBackground()
if PromptSettings.load().isEnabled {
BackgroundRefresh.submit()
}
- default:
+ @unknown default:
break
}
}
diff --git a/Reportage/Services/AppLock.swift b/Reportage/Services/AppLock.swift
@@ -0,0 +1,210 @@
+import LocalAuthentication
+import OSLog
+import SwiftUI
+
+/// Whether the app locks, and how long after it's left. Kept in
+/// `UserDefaults` on each device and never synced.
+struct AppLockSettings: Codable, Equatable, Sendable {
+ /// How long the app can be in the background before it locks again.
+ enum Delay: Int, Codable, CaseIterable, Sendable {
+ case immediately = 0
+ case oneMinute = 60
+ case fiveMinutes = 300
+ case fifteenMinutes = 900
+
+ var seconds: TimeInterval { TimeInterval(rawValue) }
+ }
+
+ var isEnabled = false
+ var delay = Delay.immediately
+
+ /// Whether the app, left for the background at `leftAt`, is locked
+ /// again on its return at `now`.
+ func locks(leftAt: Date, now: Date) -> Bool {
+ isEnabled && now.timeIntervalSince(leftAt) >= delay.seconds
+ }
+}
+
+extension AppLockSettings {
+ private static let key = "appLockSettings"
+
+ static func load(from defaults: UserDefaults = .standard) -> AppLockSettings {
+ guard let data = defaults.data(forKey: key),
+ let settings = try? JSONDecoder().decode(AppLockSettings.self, from: data)
+ else { return AppLockSettings() }
+ return settings
+ }
+
+ func save(to defaults: UserDefaults = .standard) {
+ guard let data = try? JSONEncoder().encode(self) else { return }
+ defaults.set(data, forKey: Self.key)
+ }
+}
+
+/// Locks the app behind Face ID, or the device passcode when Face ID fails
+/// or isn't set up.
+///
+/// While the app is locked, or in the background with the lock on, a window
+/// above everything else covers it, so the app switcher's snapshot shows
+/// nothing and a survey opened from a notification waits beneath until the
+/// app is unlocked. Notification actions and App Intents show nothing, so
+/// they work while locked.
+@MainActor
+@Observable
+final class AppLock {
+ private(set) var settings: AppLockSettings
+ private(set) var isLocked: Bool
+ /// Whether the cover is shown: while locked, and in the background.
+ private(set) var isCovered: Bool
+
+ /// When the app last went into the background unlocked. Only a return
+ /// from the background locks it: Face ID's own prompt and Control
+ /// Center make the app inactive without leaving it.
+ @ObservationIgnored private var leftAt: Date?
+ /// Set on leaving the app, so returning asks for Face ID once. The
+ /// prompt itself makes the app inactive and active again, which mustn't
+ /// ask again if it's cancelled.
+ @ObservationIgnored private var promptsOnReturn = true
+ @ObservationIgnored private var window: UIWindow?
+ @ObservationIgnored private var isAuthenticating = false
+ private let defaults: UserDefaults
+ private let evaluate: @MainActor (String) async -> Bool
+
+ private static let logger = Logger(subsystem: "net.inqk.reportage", category: "AppLock")
+
+ /// `evaluate` asks for the owner with a reason, and says whether they
+ /// were; tests replace it.
+ init(
+ defaults: UserDefaults = .standard,
+ evaluate: @escaping @MainActor (String) async -> Bool = AppLock.askForOwner
+ ) {
+ self.defaults = defaults
+ self.evaluate = evaluate
+ let settings = AppLockSettings.load(from: defaults)
+ self.settings = settings
+ isLocked = settings.isEnabled
+ isCovered = settings.isEnabled
+ }
+
+ /// 'Face ID', 'Touch ID' or 'Passcode', whichever unlocks the app here.
+ var methodName: LocalizedStringResource {
+ let context = LAContext()
+ _ = context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)
+ switch context.biometryType {
+ case .faceID: return "Face ID"
+ case .touchID: return "Touch ID"
+ case .opticID: return "Optic ID"
+ default: return "Passcode"
+ }
+ }
+
+ /// Whether the device can lock the app at all: it needs a passcode.
+ var isAvailable: Bool {
+ LAContext().canEvaluatePolicy(.deviceOwnerAuthentication, error: nil)
+ }
+
+ // MARK: Scene phases
+
+ func didEnterBackground(now: Date = Date()) {
+ guard settings.isEnabled else { return }
+ if !isLocked { leftAt = now }
+ promptsOnReturn = true
+ isCovered = true
+ updateWindow()
+ }
+
+ /// On launch the scene is inactive before it's active, so the cover is
+ /// up before anything else is seen.
+ func didBecomeInactive() {
+ updateWindow()
+ }
+
+ func didBecomeActive(now: Date = Date()) {
+ guard settings.isEnabled else { return }
+ if !isLocked, let leftAt, settings.locks(leftAt: leftAt, now: now) {
+ isLocked = true
+ }
+ leftAt = nil
+ if isLocked {
+ updateWindow()
+ if promptsOnReturn {
+ promptsOnReturn = false
+ Task { await unlock() }
+ }
+ } else {
+ isCovered = false
+ updateWindow()
+ }
+ }
+
+ // MARK: Unlocking
+
+ /// Asks for Face ID, falling back to the passcode, and unlocks if it
+ /// succeeds.
+ func unlock() async {
+ guard isLocked else { return }
+ guard await authenticate(reason: String(localized: "Unlock Reportage")) else { return }
+ isLocked = false
+ isCovered = false
+ updateWindow()
+ }
+
+ /// Turns the lock on or off after Face ID confirms it's the owner, so
+ /// someone holding the unlocked phone can't turn it off.
+ func setEnabled(_ isEnabled: Bool) async {
+ guard isEnabled != settings.isEnabled else { return }
+ let reason =
+ isEnabled
+ ? String(localized: "Turn on the lock for Reportage")
+ : String(localized: "Turn off the lock for Reportage")
+ guard await authenticate(reason: reason) else { return }
+ settings.isEnabled = isEnabled
+ settings.save(to: defaults)
+ }
+
+ func setDelay(_ delay: AppLockSettings.Delay) {
+ settings.delay = delay
+ settings.save(to: defaults)
+ }
+
+ private func authenticate(reason: String) async -> Bool {
+ guard !isAuthenticating else { return false }
+ isAuthenticating = true
+ defer { isAuthenticating = false }
+ return await evaluate(reason)
+ }
+
+ /// Face ID, or the passcode when it fails or isn't set up.
+ static func askForOwner(reason: String) async -> Bool {
+ do {
+ return try await LAContext().evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason)
+ } catch {
+ logger.notice("Authentication didn't succeed: \(error)")
+ return false
+ }
+ }
+
+ // MARK: Cover
+
+ /// Shows or hides the cover window. It's a window of its own because
+ /// sheets, such as a survey, are presented above anything in the app's
+ /// own window.
+ private func updateWindow() {
+ if isCovered {
+ guard window == nil, let scene = Self.windowScene else { return }
+ let window = UIWindow(windowScene: scene)
+ window.windowLevel = .alert + 1
+ window.rootViewController = UIHostingController(rootView: LockView(lock: self))
+ window.isHidden = false
+ self.window = window
+ } else {
+ window?.isHidden = true
+ window = nil
+ }
+ }
+
+ private static var windowScene: UIWindowScene? {
+ let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }
+ return scenes.first { $0.activationState == .foregroundActive } ?? scenes.first
+ }
+}
diff --git a/Reportage/Views/LockView.swift b/Reportage/Views/LockView.swift
@@ -0,0 +1,34 @@
+import SwiftUI
+
+/// What covers the app while it's locked or in the background: the app's
+/// name and, once it's in front, a button to unlock it.
+struct LockView: View {
+ let lock: AppLock
+
+ var body: some View {
+ VStack(spacing: Theme.promptGap) {
+ Spacer()
+ Text("Reportage\(Text(".").foregroundStyle(Theme.mark))", comment: "The app's name on the lock screen, with a coloured full stop")
+ .screenTitle()
+ .accessibilityLabel(Text("Reportage"))
+ Spacer()
+ if lock.isLocked {
+ Button {
+ Task { await lock.unlock() }
+ } label: {
+ Text("Unlock with \(Text(lock.methodName))", comment: "Unlocks the app; the method is Face ID, Touch ID or Passcode")
+ .font(.body.weight(.semibold))
+ .foregroundStyle(Theme.onAccent)
+ .frame(maxWidth: .infinity, minHeight: 52)
+ .background(Theme.accent, in: .capsule)
+ }
+ .buttonStyle(.plain)
+ .padding(.horizontal, Theme.margin)
+ .padding(.vertical, 12)
+ }
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .background(Theme.paper)
+ .foregroundStyle(Theme.ink)
+ }
+}
diff --git a/Reportage/Views/Settings/AppLockView.swift b/Reportage/Views/Settings/AppLockView.swift
@@ -0,0 +1,70 @@
+import SwiftUI
+
+/// Whether the app asks for Face ID, and how soon after it's left.
+struct AppLockView: View {
+ @Environment(AppLock.self) private var lock
+
+ var body: some View {
+ List {
+ Section {
+ Toggle(isOn: isEnabled) {
+ Text("Lock with \(Text(lock.methodName))", comment: "Turns the app lock on; the method is Face ID, Touch ID or Passcode")
+ }
+ .disabled(!lock.isAvailable)
+ .settingsRow()
+ .listRowSeparator(.hidden, edges: .top)
+ if lock.settings.isEnabled {
+ Picker("Require", selection: delay) {
+ ForEach(AppLockSettings.Delay.allCases, id: \.self) { delay in
+ DelayText(delay: delay).tag(delay)
+ }
+ }
+ .settingsRow()
+ }
+ SettingsNote {
+ if lock.isAvailable {
+ Text(
+ "Reportage asks for \(Text(lock.methodName)) when it's opened, and hides its contents in the app switcher. Notification actions, Instant Reports and Shortcuts still work while it's locked."
+ )
+ } else {
+ Text("Set a passcode for this iPhone to lock Reportage.")
+ }
+ }
+ }
+ }
+ .listStyle(.plain)
+ .scrollContentBackground(.hidden)
+ .tabBarClearance()
+ .background(Theme.paper)
+ .foregroundStyle(Theme.ink)
+ .navigationTitle("App Lock")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar(.visible, for: .navigationBar)
+ }
+
+ /// Changing it asks for Face ID first; the toggle stays put until then.
+ private var isEnabled: Binding<Bool> {
+ Binding(
+ get: { lock.settings.isEnabled },
+ set: { isOn in Task { await lock.setEnabled(isOn) } })
+ }
+
+ private var delay: Binding<AppLockSettings.Delay> {
+ Binding(
+ get: { lock.settings.delay },
+ set: { lock.setDelay($0) })
+ }
+}
+
+private struct DelayText: View {
+ let delay: AppLockSettings.Delay
+
+ var body: some View {
+ switch delay {
+ case .immediately: Text("Immediately")
+ case .oneMinute: Text("After 1 Minute")
+ case .fiveMinutes: Text("After 5 Minutes")
+ case .fifteenMinutes: Text("After 15 Minutes")
+ }
+ }
+}
diff --git a/Reportage/Views/Settings/SettingsView.swift b/Reportage/Views/Settings/SettingsView.swift
@@ -3,6 +3,7 @@ import SwiftUI
/// Settings: the questions, when random prompts come, and importing and
/// exporting.
struct SettingsView: View {
+ @Environment(AppLock.self) private var appLock: AppLock?
@State private var settings = PromptSettings.load()
#if DEBUG
@State private var isShowingWelcome = false
@@ -41,6 +42,21 @@ struct SettingsView: View {
WelcomeReplay { isShowingWelcome = true }
#endif
Section {
+ NavigationLink {
+ AppLockView()
+ } label: {
+ LabeledContent("App Lock") {
+ Group {
+ if let appLock, appLock.settings.isEnabled {
+ Text(appLock.methodName)
+ } else {
+ Text("Off", comment: "The app lock is turned off")
+ }
+ }
+ .foregroundStyle(Theme.accent)
+ }
+ }
+ .settingsRow()
NavigationLink("About") { AboutView() }
.settingsRow()
} header: {
diff --git a/Tests/Unit/AppLockTests.swift b/Tests/Unit/AppLockTests.swift
@@ -0,0 +1,119 @@
+import Foundation
+import Testing
+
+@testable import Reportage
+
+@MainActor
+@Suite("AppLock")
+struct AppLockTests {
+
+ /// Answers each request for the owner with `answer`, counting them.
+ @MainActor
+ private final class Owner {
+ var answer = true
+ var asked = 0
+ }
+
+ private let defaults = UserDefaults(suiteName: "AppLockTests-\(UUID().uuidString)")!
+ private let owner = Owner()
+ private let start = Date(timeIntervalSince1970: 1_000)
+
+ private func makeLock() -> AppLock {
+ let owner = owner
+ return AppLock(defaults: defaults) { _ in
+ owner.asked += 1
+ return owner.answer
+ }
+ }
+
+ /// A lock that's turned on, unlocked, with `delay`.
+ private func unlockedLock(delay: AppLockSettings.Delay = .immediately) async -> AppLock {
+ let lock = makeLock()
+ await lock.setEnabled(true)
+ lock.setDelay(delay)
+ return lock
+ }
+
+ /// Lets the request for the owner made on becoming active run.
+ private func settle() async {
+ for _ in 0..<10 { await Task.yield() }
+ }
+
+ @Test("The delay decides whether a return from the background locks")
+ func delay() {
+ var settings = AppLockSettings(isEnabled: true, delay: .oneMinute)
+ #expect(!settings.locks(leftAt: start, now: start.addingTimeInterval(59)))
+ #expect(settings.locks(leftAt: start, now: start.addingTimeInterval(60)))
+ settings.delay = .immediately
+ #expect(settings.locks(leftAt: start, now: start))
+ settings.isEnabled = false
+ #expect(!settings.locks(leftAt: start, now: start.addingTimeInterval(3_600)))
+ }
+
+ @Test("Turning the lock on or off asks for the owner, and is kept")
+ func enabling() async {
+ let lock = makeLock()
+ #expect(!lock.isLocked)
+
+ owner.answer = false
+ await lock.setEnabled(true)
+ #expect(!lock.settings.isEnabled)
+
+ owner.answer = true
+ await lock.setEnabled(true)
+ lock.setDelay(.fiveMinutes)
+ #expect(lock.settings.isEnabled)
+ #expect(!lock.isLocked)
+ #expect(owner.asked == 2)
+ #expect(AppLockSettings.load(from: defaults) == AppLockSettings(isEnabled: true, delay: .fiveMinutes))
+
+ // A new launch starts locked.
+ #expect(makeLock().isLocked)
+ }
+
+ @Test("Becoming active without leaving the app doesn't lock it")
+ func inactiveOnly() async {
+ let lock = await unlockedLock()
+ lock.didBecomeInactive()
+ lock.didBecomeActive(now: start)
+ #expect(!lock.isLocked)
+ #expect(!lock.isCovered)
+ }
+
+ @Test("A return within the delay uncovers the app without asking")
+ func withinDelay() async {
+ let lock = await unlockedLock(delay: .oneMinute)
+ lock.didEnterBackground(now: start)
+ #expect(lock.isCovered)
+ lock.didBecomeActive(now: start.addingTimeInterval(30))
+ #expect(!lock.isLocked)
+ #expect(!lock.isCovered)
+ #expect(owner.asked == 1)
+ }
+
+ @Test("A return after the delay locks and asks once, and unlocking uncovers")
+ func afterDelay() async {
+ let lock = await unlockedLock(delay: .oneMinute)
+ owner.answer = false
+ lock.didEnterBackground(now: start)
+ lock.didBecomeActive(now: start.addingTimeInterval(61))
+ #expect(lock.isLocked)
+ #expect(lock.isCovered)
+ await settle()
+ // Once to turn the lock on, and once on returning.
+ #expect(owner.asked == 2)
+ #expect(lock.isLocked)
+
+ // Face ID's prompt makes the app inactive and active again, which
+ // doesn't ask again.
+ lock.didBecomeInactive()
+ lock.didBecomeActive(now: start.addingTimeInterval(62))
+ await settle()
+ #expect(owner.asked == 2)
+
+ owner.answer = true
+ await lock.unlock()
+ #expect(!lock.isLocked)
+ #expect(!lock.isCovered)
+ }
+}
diff --git a/project.yml b/project.yml
@@ -46,6 +46,7 @@ targets:
UIBackgroundModes:
- fetch
NSHealthShareUsageDescription: Reportage records your steps and other activity so far that day with each report, and how you slept with wake reports. Health data stays on this iPhone.
+ NSFaceIDUsageDescription: Reportage uses Face ID to unlock the app when App Lock is turned on.
NSLocationWhenInUseUsageDescription: Reportage records where you are with each report, and suggests places nearby when you say where you are.
NSLocationAlwaysAndWhenInUseUsageDescription: Reportage records where you are with each report, including reports you log from a notification without opening the app.
UILaunchScreen: {}