commit 1c88f294f1f3236240a794fa33a1488562ea4313
parent 3ad5cd420734eb7cfe9731f926c8095ad0076199
Author: Michael Camilleri <[email protected]>
Date: Tue, 20 Oct 2026 08:03:42 +0900
Record activity and sleep from Health with each report
This commit reads Health for each report: steps, walking and running
distance and flights climbed from local midnight up to the report, and
for a wake report, the night's sleep with its start, end, time asleep
and time in each stage. The values appear in a Health section of the
report's details, after Sound.
Health access is asked for in the welcome, after notifications, and an
install welcomed before Health existed sees the welcome once more.
Reports filed from then on are filled in as soon as they're saved, or,
if the iPhone was locked, the next time the app comes to the
foreground, since Health can't be read while it's locked. Earlier
reports, the imported archive included, are filled in only when the
user taps 'Fill In Health Data' in Settings' Data section, which shows
a running count and can be stopped.
The values are a local cache rather than part of the report. They live
in a new HealthEntity linked to the report, apart from the synced
Context, so they never reach CloudKit; Health restores them on a new
device and App Review forbids keeping health data in iCloud. An entry
is read again until the report is a day old, by which time the Watch's
samples have reached the iPhone, and is then settled. Reportage never
writes to Health.
The iPhone and the Watch both record sleep, so only the source with the
most time asleep is used, and its samples are split into sessions an
hour or more apart, with the longest taken as the night, so a nap the
afternoon before isn't counted.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Diffstat
| M | Notes/Design.md | | | 50 | ++++++++++++++++++++++++++++++++++++-------------- |
| M | Reportage.xcodeproj/project.pbxproj | | | 32 | ++++++++++++++++++++++++++++++++ |
| M | Reportage/AppDelegate.swift | | | 1 | + |
| M | Reportage/Info.plist | | | 2 | ++ |
| M | Reportage/Reportage.entitlements | | | 4 | ++++ |
| M | Reportage/ReportageApp.swift | | | 3 | +++ |
| M | Reportage/Services/FirstLaunch.swift | | | 17 | +++++++++++------ |
| A | Reportage/Services/Health/HealthFill.swift | | | 199 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | Reportage/Services/Health/HealthReader.swift | | | 106 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | Reportage/Services/Health/SleepSummary.swift | | | 74 | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| M | Reportage/Views/Report/ReportDetailView.swift | | | 3 | ++- |
| M | Reportage/Views/Report/ReportDetails.swift | | | 31 | +++++++++++++++++++++++++++++-- |
| M | Reportage/Views/Settings/DataSection.swift | | | 30 | ++++++++++++++++++++++++++++-- |
| M | Reportage/Views/WelcomeView.swift | | | 12 | +++++++++--- |
| A | Shared/Models/HealthContext.swift | | | 43 | +++++++++++++++++++++++++++++++++++++++++++ |
| A | Shared/Persistence/HealthCache.swift | | | 82 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| M | Shared/Persistence/ReportStore.swift | | | 5 | +++-- |
| M | Shared/Persistence/ReportageModel.xcdatamodeld/ReportageModel.xcdatamodel/contents | | | 7 | +++++++ |
| A | Tests/Unit/HealthTests.swift | | | 178 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| M | Tests/Unit/ReportDetailsTests.swift | | | 20 | ++++++++++++++++++++ |
| M | Tests/Unit/SchemaMigrationTests.swift | | | 8 | +++++--- |
| M | project.yml | | | 1 | + |
22 files changed, 875 insertions(+), 33 deletions(-)
diff --git a/Notes/Design.md b/Notes/Design.md
@@ -658,13 +658,33 @@ well within the free quota). Backfilled values are tagged `source: weatherKit` a
### Health
-Read-only HealthKit access:
-
-- steps, distance and flights climbed so far today
-- activity rings: move, exercise and stand (`HKActivitySummary`)
-- the previous night's sleep (`sleepAnalysis`), attached to wake reports
-- heart rate nearest the report's time, and resting heart rate
-- environmental audio exposure (see below)
+Read-only HealthKit access, to begin with:
+
+- **Activity so far today:** steps, walking and running distance, and flights
+ climbed, from local midnight in the report's time zone up to the report.
+ Statistics queries sum them, which merges the iPhone's and the Watch's
+ samples without counting them twice.
+- **Sleep, on wake reports only:** the night before, from sleep samples in
+ the 18 hours up to the report. iPhone and Watch both record sleep, and their
+ samples overlap, so one source is used: the one with the most time asleep.
+ Its asleep samples are split into sessions wherever they're more than an
+ hour apart, so an afternoon nap isn't joined to the night, and the longest
+ session is the night. From it come when sleep started and ended, the time asleep, and the time in
+ each stage (core, deep, REM, awake) where the source records stages.
+
+Activity rings, heart rate and environmental noise may follow; they aren't
+read yet.
+
+Health access is asked for in the welcome, after location and notifications.
+An install that was welcomed before Health was asked for sees the welcome
+once more, so it can ask.
+
+Reports filed after Health was first asked for are filled in automatically:
+as soon as they're saved if the iPhone is unlocked, and otherwise the next
+time the app comes to the foreground. Earlier reports, the imported archive included, are filled in only when the
+user asks, with **Fill In Health Data** in Settings' Data section. It works
+newest first and in batches, and can be stopped and run again; it skips
+reports already settled.
Reportage never writes to HealthKit. Its own store is the record of
everything it captures; HealthKit is only read from.
@@ -691,11 +711,12 @@ and `audio` and sync with the report.
'steps today' depends on when the Watch last synced. Each cache entry
records when it was derived. It's re-derived on later launches until it is
24 hours past the report, then treated as settled.
-- **Missing values.** Each entry records why a value is absent: no samples,
- not authorised, or not attempted yet. HealthKit reports denied read access
- as empty results, so the cache can't tell 'not authorised' from 'no
- samples' for certain. It goes by the authorisation request status and
- doesn't retry settled entries unless the user asks.
+- **Missing values.** A report with no cache entry hasn't been filled in. An
+ entry with a value left out means Health had nothing for it: HealthKit
+ reports denied read access as empty results, so 'no samples' and 'not
+ allowed' look the same and the cache doesn't try to tell them apart.
+ Nothing is read until Health access has been asked for, so 'never asked'
+ is never confused with either. Settled entries aren't read again.
- **Export.** Export can include the cache, since a file the user asked for
isn't iCloud storage.
@@ -716,8 +737,9 @@ In order of preference:
the audio session.**
Microphone sampling is deferred. It needs its own permission and the route
-check verified on a device, so ambient noise waits for Health in Phase 5, and
-microphone sampling is reconsidered then.
+check verified on a device. Health noise isn't among the first Health values
+either, so ambient noise isn't recorded yet, and both are reconsidered when
+Health grows.
### Device and photos
diff --git a/Reportage.xcodeproj/project.pbxproj b/Reportage.xcodeproj/project.pbxproj
@@ -14,6 +14,8 @@
123470F9E3205890526D3A89 /* EventLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = BFF717BC324925C231BD3378 /* EventLog.swift */; };
16CDDFE25EBB07C0EA9AC5AA /* DiagnosticsSection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 87545A7909A370C668314DFF /* DiagnosticsSection.swift */; };
16D2FB106A2C588BAAB3EB06 /* PromptSchedulerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2425CB4D9B12D422467F6FD7 /* PromptSchedulerTests.swift */; };
+ 19FD732027A16A84552DFD0E /* HealthContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 86069F79CD8FA24FC6C26650 /* HealthContext.swift */; };
+ 1BB257513FDA7541960B294C /* HealthCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1F55B30D0B5E711A28CD0B1 /* HealthCache.swift */; };
226A38BE6D7171D892EA35B3 /* FirstLaunch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7CE9EDC8448889EB9D4D358E /* FirstLaunch.swift */; };
22EA393B887791E20B6FE625 /* PlacePickerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B6C4141A26EED99B1F03FBE /* PlacePickerTests.swift */; };
25BC9F95DC40E31B1E4C6FBA /* Token.swift in Sources */ = {isa = PBXBuildFile; fileRef = A3BE62142CCC4A791F05163A /* Token.swift */; };
@@ -35,6 +37,7 @@
690A6B50550B9CE4B954CC0C /* PromptScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C4665B55B0307E899595C1D /* PromptScheduler.swift */; };
6B71941AAD84B87358A969A0 /* LogPassiveReportIntent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 90F9BD4EA70DCB46924CF9B8 /* LogPassiveReportIntent.swift */; };
6E21E729F89178EBD019980E /* InlineCasing.swift in Sources */ = {isa = PBXBuildFile; fileRef = A00E589A8387E7A1E348503C /* InlineCasing.swift */; };
+ 6E6EAFD0C182B2482F6B6FBD /* HealthFill.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5CC1EB95C82F2D9B0982650 /* HealthFill.swift */; };
6F06CC539C4D17B343A9321C /* LegacyBlob.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30FFB17809ADA84F1036E2A7 /* LegacyBlob.swift */; };
7488B9EE97D419E2B6B9FCEA /* PromptNotification.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9C326FBA3249ED86912FBF5 /* PromptNotification.swift */; };
7676E79864C7C26CB9EA4B10 /* PromptSchedule.swift in Sources */ = {isa = PBXBuildFile; fileRef = 86474CD2E8EC300CD6B37BB2 /* PromptSchedule.swift */; };
@@ -48,6 +51,7 @@
89AD9247DEBDB7017EC8E017 /* reporter-fixture.json in Resources */ = {isa = PBXBuildFile; fileRef = 60457C07EF790C11D6C47EDF /* reporter-fixture.json */; };
8ADBA81D5D9ECCDCD5BDA742 /* JSONSlicerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4AFF3D49ED9E8AC69390925 /* JSONSlicerTests.swift */; };
8AF60BB296144ED9D11EA053 /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6024EA06BE24A189D4F7D0E4 /* Response.swift */; };
+ 905D1185CF8B3426ECB91AFD /* HealthTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 695CB01E79016592A3823541 /* HealthTests.swift */; };
961848A8D899BC67FA43F475 /* ReportageApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 383FF2C73A8FBAA2AB13D653 /* ReportageApp.swift */; };
964408E4D25713F627048C77 /* ModelCodingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C606A9B0EF8D84950B9681B /* ModelCodingTests.swift */; };
97BC8348B7F48AF0473691FC /* ReportStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 28AD66BC8ED4AEABF6640108 /* ReportStore.swift */; };
@@ -57,6 +61,7 @@
A1FBFB9809DD3FF52BD7E5A7 /* DataSection.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA2E66BAB2463FD51EFE9F52 /* DataSection.swift */; };
A740B635075EB81AA70ED815 /* ReportDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F498961A14F24AE6CC37453C /* ReportDetailView.swift */; };
A7C988B20CD1C937A2E776D0 /* EventLogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7DD8E44D1A1F7789F528BD3 /* EventLogTests.swift */; };
+ A93CC28A9DE5B39F41526AC5 /* SleepSummary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F8F059CE98371610A663BE7 /* SleepSummary.swift */; };
B00AC94E13BC9C602179953E /* SurveyModelTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6E382405EE9DBEC8EE616C1D /* SurveyModelTests.swift */; };
B454D3067CD611AE55E30A1D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 633FE6CD8111A433CA9BE7EC /* AppDelegate.swift */; };
B510BB2C1C11D72DFE15E3C7 /* ReportageExportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DB6FF151DCEBC3913131834 /* ReportageExportTests.swift */; };
@@ -75,6 +80,7 @@
D3FF67FB406DCCB78DF9D61A /* ReportSummaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0734316A58943D5F2E26F718 /* ReportSummaryTests.swift */; };
D487802C53EA0E96698BE151 /* ContextCapture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F3237323A968FA629020DA9 /* ContextCapture.swift */; };
D74CE3807E9593D470DADAA8 /* PlacePicker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C40E7F6C3A90E317C8CB5B1 /* PlacePicker.swift */; };
+ D7E440B08D6F133B8DD9B5C9 /* HealthReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B5C26C38B8B25086810CAB1 /* HealthReader.swift */; };
D7F95FB1236974113EBE93FA /* ReportKind+Title.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5591E042089D038B59B26E9F /* ReportKind+Title.swift */; };
D9A8839569734F5CEAC43A44 /* TokenAnswer.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF998798373C9CCAD65999B3 /* TokenAnswer.swift */; };
DF632654B427EE32C44C6F78 /* Context.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1F200EBD30BC12D2313E6C6F /* Context.swift */; };
@@ -126,6 +132,7 @@
0734316A58943D5F2E26F718 /* ReportSummaryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportSummaryTests.swift; sourceTree = "<group>"; };
0B35602A218BE4EE399835FD /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };
0E6B536B922A8468136815CD /* QuestionListTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QuestionListTests.swift; sourceTree = "<group>"; };
+ 1B5C26C38B8B25086810CAB1 /* HealthReader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HealthReader.swift; sourceTree = "<group>"; };
1B6C4141A26EED99B1F03FBE /* PlacePickerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlacePickerTests.swift; sourceTree = "<group>"; };
1BBAB5AD6266B8F6E3507AE3 /* ReportSummary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportSummary.swift; sourceTree = "<group>"; };
1C4665B55B0307E899595C1D /* PromptScheduler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PromptScheduler.swift; sourceTree = "<group>"; };
@@ -133,6 +140,7 @@
2425CB4D9B12D422467F6FD7 /* PromptSchedulerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PromptSchedulerTests.swift; sourceTree = "<group>"; };
24A77AE6DE479403D1D4C9CF /* QuestionPage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QuestionPage.swift; sourceTree = "<group>"; };
28AD66BC8ED4AEABF6640108 /* ReportStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportStore.swift; sourceTree = "<group>"; };
+ 2F8F059CE98371610A663BE7 /* SleepSummary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SleepSummary.swift; sourceTree = "<group>"; };
30FFB17809ADA84F1036E2A7 /* LegacyBlob.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LegacyBlob.swift; sourceTree = "<group>"; };
36C7E4E96538BB14AD6956CA /* HomeView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeView.swift; sourceTree = "<group>"; };
383FF2C73A8FBAA2AB13D653 /* ReportageApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportageApp.swift; sourceTree = "<group>"; };
@@ -152,6 +160,7 @@
61C0B5BB02ECDBE84F5F73FA /* PersistenceController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PersistenceController.swift; sourceTree = "<group>"; };
633FE6CD8111A433CA9BE7EC /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
643C730A99F0B7BA8C1F8A8E /* JSONSlicer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSONSlicer.swift; sourceTree = "<group>"; };
+ 695CB01E79016592A3823541 /* HealthTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HealthTests.swift; sourceTree = "<group>"; };
6E382405EE9DBEC8EE616C1D /* SurveyModelTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SurveyModelTests.swift; sourceTree = "<group>"; };
7196D553D769071DB876B606 /* ReporterTimeZones.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReporterTimeZones.swift; sourceTree = "<group>"; };
729C291798F29C69029E7DB7 /* InstantReportLogger.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InstantReportLogger.swift; sourceTree = "<group>"; };
@@ -169,6 +178,7 @@
81BA515BEA1B0B68CE0D1326 /* SettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsView.swift; sourceTree = "<group>"; };
844ABAD88442C143BA239374 /* SurveyModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SurveyModel.swift; sourceTree = "<group>"; };
84E55C093BA98D8700F406AE /* ReportStoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportStoreTests.swift; sourceTree = "<group>"; };
+ 86069F79CD8FA24FC6C26650 /* HealthContext.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HealthContext.swift; sourceTree = "<group>"; };
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>"; };
@@ -183,6 +193,7 @@
A20C574BC234EDBD4056E2B7 /* TestHelpers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TestHelpers.swift; sourceTree = "<group>"; };
A3157F7D5E4289B349E92402 /* ContextCaptureTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContextCaptureTests.swift; sourceTree = "<group>"; };
A3BE62142CCC4A791F05163A /* Token.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Token.swift; sourceTree = "<group>"; };
+ A5CC1EB95C82F2D9B0982650 /* HealthFill.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HealthFill.swift; sourceTree = "<group>"; };
A70B6E5B7C07D2CE13E9E771 /* RootView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RootView.swift; sourceTree = "<group>"; };
A7DD8E44D1A1F7789F528BD3 /* EventLogTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EventLogTests.swift; sourceTree = "<group>"; };
A8E21C29422DA372F6363365 /* EntryBuilder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EntryBuilder.swift; sourceTree = "<group>"; };
@@ -205,6 +216,7 @@
D03D0770BA2E26D7E4A7DECC /* ReportageModel.xcdatamodel */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcdatamodel; path = ReportageModel.xcdatamodel; sourceTree = "<group>"; };
D4AFF3D49ED9E8AC69390925 /* JSONSlicerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSONSlicerTests.swift; sourceTree = "<group>"; };
DB87A3E922FA7AE98B93DF1E /* PromptSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PromptSettings.swift; sourceTree = "<group>"; };
+ E1F55B30D0B5E711A28CD0B1 /* HealthCache.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HealthCache.swift; sourceTree = "<group>"; };
E21F898FF60FC3A6AFCA06E9 /* Reportage Unit Tests.xctest */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.cfbundle; path = "Reportage Unit Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
E60426297403B9F8632343D8 /* SchemaMigrationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SchemaMigrationTests.swift; sourceTree = "<group>"; };
E7F1ECC4B803EFFD88FFF52B /* ReportageExport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportageExport.swift; sourceTree = "<group>"; };
@@ -272,6 +284,16 @@
path = Report;
sourceTree = "<group>";
};
+ 3DA89C2E098DB18D7FD0CC0A /* Health */ = {
+ isa = PBXGroup;
+ children = (
+ A5CC1EB95C82F2D9B0982650 /* HealthFill.swift */,
+ 1B5C26C38B8B25086810CAB1 /* HealthReader.swift */,
+ 2F8F059CE98371610A663BE7 /* SleepSummary.swift */,
+ );
+ path = Health;
+ sourceTree = "<group>";
+ };
4C708676FBAD641AD92F8CA0 /* Reportage */ = {
isa = PBXGroup;
children = (
@@ -290,6 +312,7 @@
children = (
1F200EBD30BC12D2313E6C6F /* Context.swift */,
94DB0CA378AEF82B3CB27B67 /* DefaultQuestions.swift */,
+ 86069F79CD8FA24FC6C26650 /* HealthContext.swift */,
B007E6BACAA214C7332EF77C /* Question.swift */,
B03734F91822E7F161432075 /* Report.swift */,
6024EA06BE24A189D4F7D0E4 /* Response.swift */,
@@ -334,6 +357,7 @@
7CE9EDC8448889EB9D4D358E /* FirstLaunch.swift */,
729C291798F29C69029E7DB7 /* InstantReportLogger.swift */,
AD85758A0521ED681067B90F /* Export */,
+ 3DA89C2E098DB18D7FD0CC0A /* Health */,
96D6D46E008E39350B203328 /* Narrative */,
580063E6A7AE05D5C6C16830 /* Places */,
0CECB181B29E96DE98FDF293 /* Prompts */,
@@ -367,6 +391,7 @@
children = (
A3157F7D5E4289B349E92402 /* ContextCaptureTests.swift */,
A7DD8E44D1A1F7789F528BD3 /* EventLogTests.swift */,
+ 695CB01E79016592A3823541 /* HealthTests.swift */,
D4AFF3D49ED9E8AC69390925 /* JSONSlicerTests.swift */,
5C606A9B0EF8D84950B9681B /* ModelCodingTests.swift */,
1B6C4141A26EED99B1F03FBE /* PlacePickerTests.swift */,
@@ -446,6 +471,7 @@
isa = PBXGroup;
children = (
5BE7248E73E2859EFF232170 /* EntityMapping.swift */,
+ E1F55B30D0B5E711A28CD0B1 /* HealthCache.swift */,
30FFB17809ADA84F1036E2A7 /* LegacyBlob.swift */,
61C0B5BB02ECDBE84F5F73FA /* PersistenceController.swift */,
28AD66BC8ED4AEABF6640108 /* ReportStore.swift */,
@@ -629,6 +655,7 @@
files = (
CFB0A1F9494F1D8919F48CC5 /* ContextCaptureTests.swift in Sources */,
A7C988B20CD1C937A2E776D0 /* EventLogTests.swift in Sources */,
+ 905D1185CF8B3426ECB91AFD /* HealthTests.swift in Sources */,
8ADBA81D5D9ECCDCD5BDA742 /* JSONSlicerTests.swift in Sources */,
964408E4D25713F627048C77 /* ModelCodingTests.swift in Sources */,
22EA393B887791E20B6FE625 /* PlacePickerTests.swift in Sources */,
@@ -667,6 +694,10 @@
C71E99843CC3D9DE4468B36B /* Environment.swift in Sources */,
123470F9E3205890526D3A89 /* EventLog.swift in Sources */,
226A38BE6D7171D892EA35B3 /* FirstLaunch.swift in Sources */,
+ 1BB257513FDA7541960B294C /* HealthCache.swift in Sources */,
+ 19FD732027A16A84552DFD0E /* HealthContext.swift in Sources */,
+ 6E6EAFD0C182B2482F6B6FBD /* HealthFill.swift in Sources */,
+ D7E440B08D6F133B8DD9B5C9 /* HealthReader.swift in Sources */,
83E954F0DAC9719D2AA02111 /* HomeView.swift in Sources */,
6E21E729F89178EBD019980E /* InlineCasing.swift in Sources */,
275A9497C40065F5C77AE473 /* InstantReportLogger.swift in Sources */,
@@ -705,6 +736,7 @@
8AF60BB296144ED9D11EA053 /* Response.swift in Sources */,
FD41318BC8EEAF3208CD59B7 /* RootView.swift in Sources */,
E64BB44903A15E99126E73E5 /* SettingsView.swift in Sources */,
+ A93CC28A9DE5B39F41526AC5 /* SleepSummary.swift in Sources */,
89AC740ACEABE2AE5453E683 /* SurveyModel.swift in Sources */,
EA730F4FD060F5843CC5B422 /* SurveyView.swift in Sources */,
013407A07B79F11D51E23BD1 /* Theme.swift in Sources */,
diff --git a/Reportage/AppDelegate.swift b/Reportage/AppDelegate.swift
@@ -8,6 +8,7 @@ import UserNotifications
final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
let persistence = PersistenceController()
let inbox = PromptInbox()
+ lazy var healthFiller = HealthFiller(store: ReportStore(persistence: persistence))
private let log = EventLog.shared.category("Prompts")
diff --git a/Reportage/Info.plist b/Reportage/Info.plist
@@ -28,6 +28,8 @@ <false/> <key>LSRequiresIPhoneOS</key> <true/> + <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> <string>Reportage records where you are with each report, including reports you log from a notification without opening the app.</string> <key>NSLocationWhenInUseUsageDescription</key>
diff --git a/Reportage/Reportage.entitlements b/Reportage/Reportage.entitlements
@@ -2,6 +2,10 @@ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> + <key>com.apple.developer.healthkit</key> + <true/> + <key>com.apple.developer.healthkit.access</key> + <array/> <key>com.apple.developer.weatherkit</key> <true/> </dict>
diff --git a/Reportage/ReportageApp.swift b/Reportage/ReportageApp.swift
@@ -14,6 +14,7 @@ struct ReportageApp: App {
.environment(\.managedObjectContext, appDelegate.persistence.viewContext)
.environment(\.reportStore, ReportStore(persistence: appDelegate.persistence))
.environment(appDelegate.inbox)
+ .environment(appDelegate.healthFiller)
.tint(Theme.accent)
.task { await seedDefaultQuestions() }
}
@@ -21,6 +22,8 @@ struct ReportageApp: App {
switch phase {
case .active:
Task { await PromptScheduler().refresh() }
+ // Health can only be read while the iPhone is unlocked.
+ appDelegate.healthFiller.fillRecent()
case .background:
if PromptSettings.load().isEnabled {
BackgroundRefresh.submit()
diff --git a/Reportage/Services/FirstLaunch.swift b/Reportage/Services/FirstLaunch.swift
@@ -1,8 +1,9 @@
import CoreLocation
import UserNotifications
-/// The permissions Reportage asks for when it's first opened: location, then
-/// notifications, each after the welcome screen has said what it's for.
+/// The permissions Reportage asks for when it's first opened: location,
+/// notifications, then Health, each after the welcome screen has said what
+/// it's for.
///
/// Every report records where it was made, so location is asked for at
/// once rather than when the first report is made. It's asked for as
@@ -16,13 +17,16 @@ enum FirstLaunch {
private static let log = EventLog.shared.category("App")
/// Whether to welcome the user: the first time the app is opened, if
- /// either permission is still undecided. Someone updating from a version
- /// that asked later, with both decided, isn't welcomed.
+ /// any permission is still undecided. Someone updating from a version
+ /// that asked later, with all of them decided, isn't welcomed. An install
+ /// welcomed before Health was asked for is welcomed once more for it.
@MainActor
static func isNeeded(defaults: UserDefaults = .standard) async -> Bool {
- guard !defaults.bool(forKey: key) else { return false }
+ let health = await HealthAccess.needsAsking()
+ guard !defaults.bool(forKey: key) else { return health }
let notifications = await UNUserNotificationCenter.current().notificationSettings().authorizationStatus
- guard CLLocationManager().authorizationStatus == .notDetermined || notifications == .notDetermined else {
+ guard CLLocationManager().authorizationStatus == .notDetermined || notifications == .notDetermined || health
+ else {
defaults.set(true, forKey: key)
return false
}
@@ -35,6 +39,7 @@ enum FirstLaunch {
static func ask(store: ReportStore?, defaults: UserDefaults = .standard) async {
await askForLocation()
await askForNotifications(store: store)
+ await HealthAccess.ask(defaults: defaults)
defaults.set(true, forKey: key)
}
diff --git a/Reportage/Services/Health/HealthFill.swift b/Reportage/Services/Health/HealthFill.swift
@@ -0,0 +1,199 @@
+import CoreData
+import Foundation
+import HealthKit
+
+/// Fills in the Health cache: reads Health for reports whose entry is
+/// missing or not yet settled, newest first.
+struct HealthFill: Sendable {
+ let store: ReportStore
+ let reader: any HealthReading
+ /// How long after a report its Health is taken to have stopped changing.
+ var settleAfter: TimeInterval = 24 * 60 * 60
+ /// How far before a wake report to look for the night's sleep.
+ var sleepWindow: TimeInterval = 18 * 60 * 60
+ var batchSize = 50
+
+ /// Fills the reports dated before `before`, and on or after `since` if
+ /// given, and returns how many it read. `progress` is told the running
+ /// count after each batch. Health being locked, or any other error from
+ /// it, ends the pass; what was read before it is kept.
+ @discardableResult
+ func fill(
+ since: Date? = nil, before: Date, now: Date = Date(),
+ progress: (@Sendable (Int) async -> Void)? = nil
+ ) async throws -> Int {
+ var cursor = before
+ var count = 0
+ while true {
+ try Task.checkCancellation()
+ let targets = try await store.healthTargets(since: since, before: cursor, limit: batchSize)
+ guard let last = targets.last else { break }
+ for target in targets {
+ try Task.checkCancellation()
+ try await store.setHealth(read(target, now: now), for: target.id)
+ count += 1
+ }
+ await progress?(count)
+ // Entries that aren't settled yet would be found again, so the
+ // next batch starts after this one.
+ cursor = last.date
+ }
+ return count
+ }
+
+ func read(_ target: HealthTarget, now: Date) async throws -> HealthRecord {
+ var calendar = Calendar(identifier: .gregorian)
+ calendar.timeZone = TimeZone(identifier: target.timeZone) ?? .current
+ var health = HealthContext()
+ let activity = try await reader.activity(from: calendar.startOfDay(for: target.date), to: target.date)
+ if activity != ActivityHealth() {
+ health.activity = activity
+ }
+ if target.kind == .wake {
+ let samples = try await reader.sleepSamples(
+ from: target.date.addingTimeInterval(-sleepWindow), to: target.date)
+ health.sleep = SleepHealth(samples: samples)
+ }
+ return HealthRecord(
+ health: health, derivedAt: now,
+ isSettled: now >= target.date.addingTimeInterval(settleAfter))
+ }
+}
+
+/// Asking for Health access, and when it was first asked for. Reports from
+/// then on are filled in automatically; earlier ones only when the user asks.
+@MainActor
+enum HealthAccess {
+ private static let key = "healthAskedAt"
+ private static let log = EventLog.shared.category("Health")
+
+ static var isAvailable: Bool { HKHealthStore.isHealthDataAvailable() }
+
+ /// Whether asking would show Health's access sheet.
+ static func needsAsking(store: HKHealthStore = HKHealthStore()) async -> Bool {
+ guard isAvailable else { return false }
+ let status = try? await store.statusForAuthorizationRequest(toShare: [], read: HealthKitReader.readTypes)
+ return status == .shouldRequest
+ }
+
+ static func ask(store: HKHealthStore = HKHealthStore(), defaults: UserDefaults = .standard) async {
+ guard await needsAsking(store: store) else { return }
+ do {
+ try await store.requestAuthorization(toShare: [], read: HealthKitReader.readTypes)
+ log.info("Asked for Health access")
+ } catch {
+ log.error("Couldn't ask for Health access: \(error)")
+ return
+ }
+ if defaults.object(forKey: key) == nil {
+ defaults.set(Date(), forKey: key)
+ }
+ }
+
+ /// When Health access was first asked for, or `nil` if it hasn't been.
+ /// Access asked for some other way, as it may be after a restore, counts
+ /// from the first time this finds it.
+ static func askedAt(store: HKHealthStore = HKHealthStore(), defaults: UserDefaults = .standard) async -> Date? {
+ if let date = defaults.object(forKey: key) as? Date { return date }
+ guard isAvailable,
+ (try? await store.statusForAuthorizationRequest(toShare: [], read: HealthKitReader.readTypes))
+ == .unnecessary
+ else { return nil }
+ let now = Date()
+ defaults.set(now, forKey: key)
+ return now
+ }
+}
+
+/// Runs Health passes for the app: reports filed since Health was asked for,
+/// each time the app comes to the foreground and whenever a report is filed,
+/// and earlier reports when the user asks. Health can only be read while the
+/// iPhone is unlocked, so a report filed while it's locked waits for the app
+/// to come to the foreground.
+@MainActor
+@Observable
+final class HealthFiller {
+ /// How many earlier reports have been filled in, while that pass runs.
+ private(set) var pastCount: Int?
+
+ @ObservationIgnored private let store: ReportStore
+ @ObservationIgnored private let healthStore = HKHealthStore()
+ @ObservationIgnored private var recentTask: Task<Void, Never>?
+ @ObservationIgnored private var pastTask: Task<Void, Never>?
+ /// Whether a report was filed while a recent pass was running.
+ @ObservationIgnored private var isRecentStale = false
+ @ObservationIgnored private var observer: (any NSObjectProtocol)?
+ private static let log = EventLog.shared.category("Health")
+
+ init(store: ReportStore) {
+ self.store = store
+ let coordinator = store.persistence.container.persistentStoreCoordinator
+ observer = NotificationCenter.default.addObserver(
+ forName: NSManagedObjectContext.didSaveObjectIDsNotification, object: nil, queue: nil
+ ) { [weak self] notification in
+ guard (notification.object as? NSManagedObjectContext)?.persistentStoreCoordinator === coordinator,
+ let inserted = notification.userInfo?[NSInsertedObjectIDsKey] as? Set<NSManagedObjectID>,
+ inserted.contains(where: { $0.entity.name == "ReportEntity" })
+ else { return }
+ Task { @MainActor in self?.fillRecent() }
+ }
+ }
+
+ private var fill: HealthFill {
+ HealthFill(store: store, reader: HealthKitReader(store: healthStore))
+ }
+
+ func fillRecent() {
+ guard recentTask == nil else {
+ isRecentStale = true
+ return
+ }
+ recentTask = Task {
+ guard let since = await HealthAccess.askedAt(store: healthStore) else {
+ recentTask = nil
+ return
+ }
+ repeat {
+ isRecentStale = false
+ do {
+ let count = try await fill.fill(since: since, before: .distantFuture)
+ if count > 0 { Self.log.info("Read Health for \(count) recent reports") }
+ } catch {
+ Self.log.error("Couldn't read Health for recent reports: \(error)")
+ isRecentStale = false
+ }
+ } while isRecentStale
+ recentTask = nil
+ }
+ }
+
+ var isFillingPast: Bool { pastCount != nil }
+
+ func fillPast() {
+ guard pastTask == nil else { return }
+ pastCount = 0
+ pastTask = Task {
+ defer {
+ pastTask = nil
+ pastCount = nil
+ }
+ // Reports filed before Health was asked for. Nothing is read
+ // until it has been.
+ guard let since = await HealthAccess.askedAt(store: healthStore) else { return }
+ do {
+ let count = try await fill.fill(before: since) { count in
+ await MainActor.run { self.pastCount = count }
+ }
+ Self.log.info("Read Health for \(count) earlier reports")
+ } catch is CancellationError {
+ Self.log.info("Stopped reading Health for earlier reports")
+ } catch {
+ Self.log.error("Couldn't read Health for earlier reports: \(error)")
+ }
+ }
+ }
+
+ func stopPast() {
+ pastTask?.cancel()
+ }
+}
diff --git a/Reportage/Services/Health/HealthReader.swift b/Reportage/Services/Health/HealthReader.swift
@@ -0,0 +1,106 @@
+import Foundation
+import HealthKit
+
+/// Reads what the Health cache holds. Replaced in tests.
+protocol HealthReading: Sendable {
+ /// Activity summed over `start..<end`.
+ func activity(from start: Date, to end: Date) async throws -> ActivityHealth
+ /// Sleep samples overlapping `start..<end`.
+ func sleepSamples(from start: Date, to end: Date) async throws -> [SleepSample]
+}
+
+/// One sleep sample, as Health recorded it.
+struct SleepSample: Equatable, Sendable {
+ enum Stage: Equatable, Sendable {
+ case inBed
+ /// Asleep, from a source that doesn't record stages.
+ case asleep
+ case core
+ case deep
+ case rem
+ case awake
+ }
+
+ /// The bundle identifier of the app or device that recorded it.
+ var source: String
+ var stage: Stage
+ var start: Date
+ var end: Date
+}
+
+struct HealthKitReader: HealthReading {
+ static let readTypes: Set<HKObjectType> = [
+ HKQuantityType(.stepCount),
+ HKQuantityType(.distanceWalkingRunning),
+ HKQuantityType(.flightsClimbed),
+ HKCategoryType(.sleepAnalysis),
+ ]
+
+ let store: HKHealthStore
+
+ func activity(from start: Date, to end: Date) async throws -> ActivityHealth {
+ async let steps = sum(.stepCount, unit: .count(), from: start, to: end)
+ async let distance = sum(.distanceWalkingRunning, unit: .meter(), from: start, to: end)
+ async let flights = sum(.flightsClimbed, unit: .count(), from: start, to: end)
+ return try await ActivityHealth(
+ steps: steps.map { Int($0.rounded()) },
+ distance: distance,
+ flightsClimbed: flights.map { Int($0.rounded()) })
+ }
+
+ func sleepSamples(from start: Date, to end: Date) async throws -> [SleepSample] {
+ let descriptor = HKSampleQueryDescriptor(
+ predicates: [
+ .categorySample(
+ type: HKCategoryType(.sleepAnalysis),
+ predicate: HKQuery.predicateForSamples(withStart: start, end: end))
+ ],
+ sortDescriptors: [SortDescriptor(\.startDate)])
+ return try await Self.ignoringNoData(default: []) {
+ try await descriptor.result(for: store).compactMap { sample in
+ guard let stage = Self.stage(sample.value) else { return nil }
+ return SleepSample(
+ source: sample.sourceRevision.source.bundleIdentifier,
+ stage: stage, start: sample.startDate, end: sample.endDate)
+ }
+ }
+ }
+
+ /// The sum over the interval, or `nil` if Health has no samples. Statistics
+ /// merge overlapping samples from the iPhone and the Watch.
+ private func sum(
+ _ identifier: HKQuantityTypeIdentifier, unit: HKUnit, from start: Date, to end: Date
+ ) async throws -> Double? {
+ let descriptor = HKStatisticsQueryDescriptor(
+ predicate: .quantitySample(
+ type: HKQuantityType(identifier),
+ predicate: HKQuery.predicateForSamples(withStart: start, end: end)),
+ options: .cumulativeSum)
+ return try await Self.ignoringNoData(default: nil) {
+ try await descriptor.result(for: store)?.sumQuantity()?.doubleValue(for: unit)
+ }
+ }
+
+ /// Health answers some queries for which it has nothing with an error
+ /// rather than an empty result. Other errors, such as the store being
+ /// locked, are thrown.
+ private static func ignoringNoData<T>(default value: T, _ body: () async throws -> T) async throws -> T {
+ do {
+ return try await body()
+ } catch let error as HKError where error.code == .errorNoData {
+ return value
+ }
+ }
+
+ private static func stage(_ value: Int) -> SleepSample.Stage? {
+ switch HKCategoryValueSleepAnalysis(rawValue: value) {
+ case .inBed: .inBed
+ case .asleepUnspecified: .asleep
+ case .asleepCore: .core
+ case .asleepDeep: .deep
+ case .asleepREM: .rem
+ case .awake: .awake
+ default: nil
+ }
+ }
+}
diff --git a/Reportage/Services/Health/SleepSummary.swift b/Reportage/Services/Health/SleepSummary.swift
@@ -0,0 +1,74 @@
+import Foundation
+
+extension SleepHealth {
+ /// Asleep samples closer together than this are one session.
+ static let sessionGap: TimeInterval = 60 * 60
+
+ /// The longest sleep session in `samples`, from a single source.
+ ///
+ /// The iPhone and the Watch both record sleep, and their samples overlap,
+ /// so adding them up would count the night twice. The source with the
+ /// most time asleep is used on its own. Its asleep samples are split into
+ /// sessions where they're more than `sessionGap` apart, so a nap the
+ /// afternoon before isn't joined to the night, and the longest session is
+ /// the night.
+ init?(samples: [SleepSample]) {
+ let bySource = Dictionary(grouping: samples, by: \.source)
+ let best = bySource.values.max { a, b in
+ Self.asleep(in: a) < Self.asleep(in: b)
+ }
+ guard let best else { return nil }
+ let asleep = best.filter { $0.stage.isAsleep }.sorted { $0.start < $1.start }
+ var sessions: [[SleepSample]] = []
+ for sample in asleep {
+ if let last = sessions.last?.last, sample.start.timeIntervalSince(last.end) <= Self.sessionGap {
+ sessions[sessions.count - 1].append(sample)
+ } else {
+ sessions.append([sample])
+ }
+ }
+ guard let night = sessions.max(by: { Self.asleep(in: $0) < Self.asleep(in: $1) }),
+ let start = night.map(\.start).min(), let end = night.map(\.end).max()
+ else { return nil }
+ let span = start..<end
+ func total(_ stage: SleepSample.Stage) -> TimeInterval {
+ best.filter { $0.stage == stage }.reduce(0) { $0 + Self.overlap($1, span) }
+ }
+ let hasStages = night.contains { $0.stage != .asleep }
+ self.init(
+ start: start,
+ end: end,
+ asleep: Self.asleep(in: night),
+ core: hasStages ? total(.core) : nil,
+ deep: hasStages ? total(.deep) : nil,
+ rem: hasStages ? total(.rem) : nil,
+ awake: hasStages ? total(.awake) : nil)
+ }
+
+ /// Time asleep, with overlapping samples counted once.
+ private static func asleep(in samples: [SleepSample]) -> TimeInterval {
+ var total: TimeInterval = 0
+ var reach = Date.distantPast
+ for sample in samples.filter({ $0.stage.isAsleep }).sorted(by: { $0.start < $1.start }) {
+ let start = max(sample.start, reach)
+ if sample.end > start { total += sample.end.timeIntervalSince(start) }
+ reach = max(reach, sample.end)
+ }
+ return total
+ }
+
+ private static func overlap(_ sample: SleepSample, _ span: Range<Date>) -> TimeInterval {
+ let start = max(sample.start, span.lowerBound)
+ let end = min(sample.end, span.upperBound)
+ return max(0, end.timeIntervalSince(start))
+ }
+}
+
+extension SleepSample.Stage {
+ var isAsleep: Bool {
+ switch self {
+ case .asleep, .core, .deep, .rem: true
+ case .inBed, .awake: false
+ }
+ }
+}
diff --git a/Reportage/Views/Report/ReportDetailView.swift b/Reportage/Views/Report/ReportDetailView.swift
@@ -103,7 +103,8 @@ struct ReportDetailPage: View {
let onDelete: () -> Void
var body: some View {
- let details = ReportDetails(report: report, lookup: describer.lookup)
+ let health = try? entity.health?.record().health
+ let details = ReportDetails(report: report, health: health, lookup: describer.lookup)
let isInstant = report.state == .passive
VStack(alignment: .leading, spacing: Theme.blockGap) {
ReportDetailHeader(report: report, isInstant: isInstant)
diff --git a/Reportage/Views/Report/ReportDetails.swift b/Reportage/Views/Report/ReportDetails.swift
@@ -25,7 +25,7 @@ struct ReportDetails: Equatable {
struct Section: Equatable {
enum Kind: Equatable {
- case time, place, location, weather, device, motion, sound, photos, record
+ case time, place, location, weather, device, motion, sound, health, photos, record
}
var kind: Kind
@@ -36,7 +36,9 @@ struct ReportDetails: Equatable {
var answers: [Answer]
var sections: [Section]
- init(report: Report, lookup: SummaryLookup, locale: Locale = .current) {
+ /// `health` is the report's Health cache, which isn't part of the
+ /// report itself.
+ init(report: Report, health: HealthContext? = nil, lookup: SummaryLookup, locale: Locale = .current) {
let format = Formatter(zone: TimeZone(identifier: report.timeZone) ?? .current, locale: locale)
answers = report.responses.map { response in
let value: Answer.Value =
@@ -56,6 +58,7 @@ struct ReportDetails: Equatable {
context.device.map { Self.device($0, format) },
context.motion.map { Self.motion($0, format) },
context.audio.map { Self.audio($0, format) },
+ health.map { Self.health($0, format) },
context.photos.map { Self.photos($0, format) },
Self.record(report, format),
]
@@ -213,6 +216,24 @@ struct ReportDetails: Equatable {
return Section(kind: .sound, title: String(localized: "Sound"), rows: rows.compactMap { $0 })
}
+ private static func health(_ health: HealthContext, _ f: Formatter) -> Section {
+ let activity = health.activity
+ let sleep = health.sleep
+ let rows = [
+ row("Steps Today", activity?.steps.map { $0.formatted() }),
+ row("Distance Today", activity?.distance.flatMap(f.distance)),
+ row("Flights Climbed Today", activity?.flightsClimbed.map { $0.formatted() }),
+ row("Fell Asleep", sleep.map { f.time($0.start) }),
+ row("Woke", sleep.map { f.time($0.end) }),
+ row("Time Asleep", sleep.map { f.duration($0.asleep) }),
+ row("Deep Sleep", sleep?.deep.map(f.duration)),
+ row("Core Sleep", sleep?.core.map(f.duration)),
+ row("REM Sleep", sleep?.rem.map(f.duration)),
+ row("Time Awake", sleep?.awake.map(f.duration)),
+ ]
+ return Section(kind: .health, title: String(localized: "Health"), rows: rows.compactMap { $0 })
+ }
+
private static func photos(_ photos: PhotosContext, _ f: Formatter) -> Section {
var rows = [row("Taken Since Last Report", photos.count.formatted())]
for (index, photo) in photos.photos.enumerated() {
@@ -305,6 +326,12 @@ private struct Formatter {
return measurement(Measurement(value: value, unit: UnitLength.meters), usage: .asProvided)
}
+ /// A distance travelled in metres, in the locale's units for roads.
+ func distance(_ value: Double) -> String? {
+ guard value >= 0 else { return nil }
+ return measurement(Measurement(value: value, unit: UnitLength.meters), usage: .road)
+ }
+
/// Metres per second, shown per hour. Negative speeds are invalid.
func speed(_ value: Double) -> String? {
guard value >= 0 else { return nil }
diff --git a/Reportage/Views/Settings/DataSection.swift b/Reportage/Views/Settings/DataSection.swift
@@ -3,9 +3,11 @@ import OSLog
import SwiftUI
import UniformTypeIdentifiers
-/// Importing a Reporter export and exporting the store as JSON.
+/// Importing a Reporter export, exporting the store as JSON, and filling in
+/// Health data for earlier reports.
struct DataSection: View {
@Environment(\.reportStore) private var store
+ @Environment(HealthFiller.self) private var healthFiller: HealthFiller?
@State private var task: DataTask?
@State private var isChoosingImport = false
@State private var includeLegacy = false
@@ -55,12 +57,36 @@ struct DataSection: View {
"Saves every question, answer and report as a JSON file. Reporter snapshots are the original records of imported reports, kept exactly as Reporter exported them."
)
}
+ if let healthFiller {
+ Button {
+ if healthFiller.isFillingPast {
+ healthFiller.stopPast()
+ } else {
+ healthFiller.fillPast()
+ }
+ } label: {
+ TaskLabel(
+ healthFiller.isFillingPast ? "Stop Filling In Health Data" : "Fill In Health Data",
+ isRunning: healthFiller.isFillingPast)
+ }
+ .disabled(task != nil || store == nil)
+ .settingsRow()
+ SettingsNote {
+ if let count = healthFiller.pastCount {
+ Text("Filled in \(count) reports so far. Keep Reportage open until it finishes.")
+ } else {
+ Text(
+ "Adds Health data to reports filed before Reportage was given access to Health, including imported reports. Newer reports are filled in automatically."
+ )
+ }
+ }
+ }
Button(role: .destructive) {
isConfirmingDelete = true
} label: {
TaskLabel("Delete All Data", isRunning: task == .deleting)
}
- .disabled(task != nil || store == nil)
+ .disabled(task != nil || store == nil || healthFiller?.isFillingPast == true)
.settingsRow()
SettingsNote {
Text(
diff --git a/Reportage/Views/WelcomeView.swift b/Reportage/Views/WelcomeView.swift
@@ -1,8 +1,8 @@
import SwiftUI
/// Shown the first time the app is opened: what Reportage does, and why it's
-/// about to ask for location and notifications. Continue asks for each in
-/// turn and closes once both are answered.
+/// about to ask for location, notifications and Health. Continue asks for
+/// each in turn and closes once all are answered.
struct WelcomeView: View {
@Environment(\.reportStore) private var store
@State private var isAsking = false
@@ -70,8 +70,14 @@ struct WelcomeContent: View {
detail:
"Prompts are delivered as system notifications. You can choose the frequency and the hours during which you want to be prompted in the Settings tab."
)
+ WelcomePermission(
+ title: "Health",
+ systemImage: "heart",
+ detail:
+ "Each report records your steps and other activity so far that day, and wake reports record how you slept. Health data stays on this iPhone."
+ )
}
- Text("You can change either permission at any time in the Settings app.")
+ Text("You can change these permissions at any time in the Settings app.")
.font(.footnote)
.foregroundStyle(Theme.muted)
}
diff --git a/Shared/Models/HealthContext.swift b/Shared/Models/HealthContext.swift
@@ -0,0 +1,43 @@
+import Foundation
+
+/// What Health had for a report. It's a local cache, filled in after the
+/// report is filed and never synced: HealthKit already syncs Health data, so
+/// another device rebuilds it from its own store. A value left out means
+/// Health had nothing for it, which includes Health access being denied.
+struct HealthContext: Codable, Hashable, Sendable {
+ var activity: ActivityHealth?
+ /// Only for wake reports: the night before.
+ var sleep: SleepHealth?
+}
+
+/// Activity from local midnight in the report's time zone up to the report.
+struct ActivityHealth: Codable, Hashable, Sendable {
+ var steps: Int?
+ /// Walking and running, metres.
+ var distance: Double?
+ var flightsClimbed: Int?
+}
+
+/// One sleep session, from a single source.
+struct SleepHealth: Codable, Hashable, Sendable {
+ var start: Date
+ var end: Date
+ /// Seconds asleep, in any stage.
+ var asleep: TimeInterval
+ /// Seconds in each stage, where the source records stages.
+ var core: TimeInterval?
+ var deep: TimeInterval?
+ var rem: TimeInterval?
+ /// Seconds awake between falling asleep and waking.
+ var awake: TimeInterval?
+}
+
+/// A report's Health cache entry.
+struct HealthRecord: Equatable, Sendable {
+ var health: HealthContext
+ /// When it was read from Health.
+ var derivedAt: Date
+ /// Whether Health is taken to have finished changing for the report, so
+ /// it isn't read again.
+ var isSettled: Bool
+}
diff --git a/Shared/Persistence/HealthCache.swift b/Shared/Persistence/HealthCache.swift
@@ -0,0 +1,82 @@
+import CoreData
+import Foundation
+
+/// A report to read Health for.
+struct HealthTarget: Equatable, Sendable {
+ var id: UUID
+ var date: Date
+ var timeZone: String
+ var kind: ReportKind
+}
+
+extension ReportStore {
+ /// Reports whose Health cache entry is missing or not yet settled, newest
+ /// first: those dated before `before`, and on or after `since` if given.
+ func healthTargets(since: Date? = nil, before: Date, limit: Int) async throws -> [HealthTarget] {
+ let context = persistence.newBackgroundContext()
+ return try await context.perform {
+ let request = ReportEntity.fetchRequest()
+ var predicates = [
+ NSPredicate(format: "date < %@", before as NSDate),
+ NSPredicate(format: "health == nil OR health.isSettled == NO"),
+ ]
+ if let since {
+ predicates.append(NSPredicate(format: "date >= %@", since as NSDate))
+ }
+ request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicates)
+ request.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
+ request.fetchLimit = limit
+ return try context.fetch(request).compactMap { entity in
+ guard let id = entity.id, let date = entity.date, let timeZone = entity.timeZone,
+ let kind = entity.kind.flatMap(ReportKind.init(rawValue:))
+ else { return nil }
+ return HealthTarget(id: id, date: date, timeZone: timeZone, kind: kind)
+ }
+ }
+ }
+
+ /// Saves a report's Health cache entry, replacing any earlier one. The
+ /// report's `modifiedAt` is left alone: the cache isn't part of the
+ /// report and is never synced.
+ func setHealth(_ record: HealthRecord, for id: UUID) async throws {
+ let context = persistence.newBackgroundContext()
+ try await context.perform {
+ let request = ReportEntity.fetchRequest()
+ request.predicate = NSPredicate(format: "id == %@", id as CVarArg)
+ request.fetchLimit = 1
+ guard let report = try context.fetch(request).first else { return }
+ let entity = report.health ?? HealthEntity(context: context)
+ try entity.update(from: record)
+ entity.report = report
+ try context.save()
+ }
+ }
+
+ func health(for id: UUID) async throws -> HealthRecord? {
+ let context = persistence.newBackgroundContext()
+ return try await context.perform {
+ let request = HealthEntity.fetchRequest()
+ request.predicate = NSPredicate(format: "report.id == %@", id as CVarArg)
+ request.fetchLimit = 1
+ return try context.fetch(request).first?.record()
+ }
+ }
+}
+
+extension HealthEntity {
+ func update(from record: HealthRecord) throws {
+ values = try ModelCoding.encode(record.health)
+ derivedAt = record.derivedAt
+ isSettled = record.isSettled
+ }
+
+ func record() throws -> HealthRecord {
+ guard let values, let derivedAt else {
+ throw EntityMappingError.missingField(entity: "Health", field: "values/derivedAt")
+ }
+ return HealthRecord(
+ health: try ModelCoding.decode(HealthContext.self, from: values),
+ derivedAt: derivedAt,
+ isSettled: isSettled)
+ }
+}
diff --git a/Shared/Persistence/ReportStore.swift b/Shared/Persistence/ReportStore.swift
@@ -215,8 +215,9 @@ struct ReportStore: Sendable {
func deleteAll() async throws {
let context = persistence.newBackgroundContext()
let viewContext = persistence.viewContext
- // Responses go with their reports, by the cascade.
- let entities = ["ReportEntity", "TokenEntity", "QuestionEntity"]
+ // Responses go with their reports, by the cascade. Health entries
+ // are named, so their deletions are reported like the rest.
+ let entities = ["ReportEntity", "HealthEntity", "TokenEntity", "QuestionEntity"]
let deleted = try await context.perform {
// Batch deletes run in SQLite without loading each object; the
// in-memory stores tests use don't support them.
diff --git a/Shared/Persistence/ReportageModel.xcdatamodeld/ReportageModel.xcdatamodel/contents b/Shared/Persistence/ReportageModel.xcdatamodeld/ReportageModel.xcdatamodel/contents
@@ -29,6 +29,7 @@
<attribute name="state" attributeType="String"/>
<attribute name="timeZone" attributeType="String"/>
<attribute name="trigger" attributeType="String"/>
+ <relationship name="health" optional="YES" maxCount="1" deletionRule="Cascade" destinationEntity="HealthEntity" inverseName="report" inverseEntity="HealthEntity"/>
<relationship name="responses" toMany="YES" deletionRule="Cascade" destinationEntity="ResponseEntity" inverseName="report" inverseEntity="ResponseEntity"/>
<uniquenessConstraints>
<uniquenessConstraint>
@@ -59,6 +60,12 @@
<fetchIndexElement property="questionID" type="Binary" order="ascending"/>
</fetchIndex>
</entity>
+ <entity name="HealthEntity" representedClassName="HealthEntity" syncable="YES" codeGenerationType="class">
+ <attribute name="derivedAt" attributeType="Date" usesScalarValueType="NO"/>
+ <attribute name="isSettled" attributeType="Boolean" defaultValueString="NO" usesScalarValueType="YES"/>
+ <attribute name="values" attributeType="Binary"/>
+ <relationship name="report" optional="YES" maxCount="1" deletionRule="Nullify" destinationEntity="ReportEntity" inverseName="health" inverseEntity="ReportEntity"/>
+ </entity>
<entity name="ResponseEntity" representedClassName="ResponseEntity" syncable="YES" codeGenerationType="class">
<attribute name="order" attributeType="Integer 16" defaultValueString="0" usesScalarValueType="YES"/>
<attribute name="prompt" attributeType="String"/>
diff --git a/Tests/Unit/HealthTests.swift b/Tests/Unit/HealthTests.swift
@@ -0,0 +1,178 @@
+import CoreData
+import Foundation
+import Testing
+
+@testable import Reportage
+
+/// Health as a test sets it up, recording what it was asked for.
+private actor FakeHealthReader: HealthReading {
+ var activity = ActivityHealth(steps: 4321, distance: 3200, flightsClimbed: 5)
+ var sleep: [SleepSample] = []
+ private(set) var activityCalls: [Range<Date>] = []
+ private(set) var sleepCalls: [Range<Date>] = []
+
+ init(sleep: [SleepSample] = []) {
+ self.sleep = sleep
+ }
+
+ func activity(from start: Date, to end: Date) async throws -> ActivityHealth {
+ activityCalls.append(start..<end)
+ return activity
+ }
+
+ func sleepSamples(from start: Date, to end: Date) async throws -> [SleepSample] {
+ sleepCalls.append(start..<end)
+ return sleep
+ }
+}
+
+@Suite("Sleep summary")
+struct SleepSummaryTests {
+
+ /// 22:00 UTC on 1 October 2026.
+ private static let evening = Date(timeIntervalSince1970: 1_790_892_000)
+
+ private static func sample(
+ _ source: String, _ stage: SleepSample.Stage, from start: Double, to end: Double
+ ) -> SleepSample {
+ SleepSample(
+ source: source, stage: stage,
+ start: evening.addingTimeInterval(start * 3600), end: evening.addingTimeInterval(end * 3600))
+ }
+
+ @Test("The source with the most sleep is used alone, with its stages")
+ func bestSource() throws {
+ let sleep = try #require(
+ SleepHealth(samples: [
+ Self.sample("phone", .inBed, from: 0, to: 9),
+ Self.sample("phone", .asleep, from: 1, to: 6),
+ Self.sample("watch", .core, from: 1, to: 3),
+ Self.sample("watch", .awake, from: 3, to: 3.5),
+ Self.sample("watch", .deep, from: 3.5, to: 5),
+ Self.sample("watch", .rem, from: 5, to: 8),
+ ]))
+ #expect(sleep.start == Self.evening.addingTimeInterval(3600))
+ #expect(sleep.end == Self.evening.addingTimeInterval(8 * 3600))
+ #expect(sleep.asleep == 6.5 * 3600)
+ #expect(sleep.core == TimeInterval(2 * 3600))
+ #expect(sleep.deep == 1.5 * 3600)
+ #expect(sleep.rem == TimeInterval(3 * 3600))
+ #expect(sleep.awake == 0.5 * 3600)
+ }
+
+ @Test("A nap well before the night isn't joined to it")
+ func napLeftOut() throws {
+ let sleep = try #require(
+ SleepHealth(samples: [
+ Self.sample("watch", .core, from: -8, to: -7),
+ Self.sample("watch", .core, from: 1, to: 7),
+ ]))
+ #expect(sleep.start == Self.evening.addingTimeInterval(3600))
+ #expect(sleep.asleep == 6 * 3600)
+ }
+
+ @Test("A source without stages records time asleep only, and no sleep is nil")
+ func unstaged() throws {
+ let sleep = try #require(SleepHealth(samples: [Self.sample("phone", .asleep, from: 0, to: 7)]))
+ #expect(sleep.asleep == 7 * 3600)
+ #expect(sleep.core == nil && sleep.deep == nil && sleep.rem == nil && sleep.awake == nil)
+ #expect(SleepHealth(samples: [Self.sample("phone", .inBed, from: 0, to: 7)]) == nil)
+ #expect(SleepHealth(samples: []) == nil)
+ }
+}
+
+@Suite("Health cache")
+struct HealthCacheTests {
+
+ private let persistence = makeTestPersistence()
+
+ private var store: ReportStore { ReportStore(persistence: persistence) }
+
+ /// 09:00 in Tokyo on 2 October 2026.
+ private static let morning = Date(timeIntervalSince1970: 1_790_985_600)
+
+ private static func report(_ number: Int, hoursAgo: Double, kind: ReportKind = .random) -> Report {
+ Report(
+ id: Fixtures.reportID(number),
+ date: morning.addingTimeInterval(-hoursAgo * 3600),
+ timeZone: "Asia/Tokyo",
+ kind: kind,
+ trigger: .app,
+ state: .complete,
+ modifiedAt: Date(timeIntervalSince1970: 0))
+ }
+
+ private func fill(_ reader: FakeHealthReader) -> HealthFill {
+ HealthFill(store: store, reader: reader, batchSize: 2)
+ }
+
+ @Test("Activity is read from local midnight, and sleep only for wake reports")
+ func reads() async throws {
+ let reader = FakeHealthReader(sleep: [
+ SleepSample(
+ source: "watch", stage: .core,
+ start: Self.morning.addingTimeInterval(-8 * 3600), end: Self.morning.addingTimeInterval(-3600))
+ ])
+ try await store.insert(Self.report(1, hoursAgo: 0, kind: .wake))
+ try await store.insert(Self.report(2, hoursAgo: 1))
+ try await fill(reader).fill(before: .distantFuture, now: Self.morning)
+
+ let midnight = Date(timeIntervalSince1970: 1_790_953_200)
+ #expect(await reader.activityCalls.map(\.lowerBound) == [midnight, midnight])
+ #expect(await reader.sleepCalls == [Self.morning.addingTimeInterval(-18 * 3600)..<Self.morning])
+
+ let wake = try #require(try await store.health(for: Fixtures.reportID(1)))
+ #expect(wake.health.activity?.steps == 4321)
+ #expect(wake.health.sleep?.asleep == TimeInterval(7 * 3600))
+ #expect(wake.derivedAt == Self.morning)
+ let random = try #require(try await store.health(for: Fixtures.reportID(2)))
+ #expect(random.health.sleep == nil)
+ }
+
+ @Test("Entries settle a day after the report, and only unsettled ones are read again")
+ func settling() async throws {
+ let reader = FakeHealthReader()
+ try await store.insert(Self.report(1, hoursAgo: 2))
+ try await store.insert(Self.report(2, hoursAgo: 30))
+ try await store.insert(Self.report(3, hoursAgo: 50))
+ #expect(try await fill(reader).fill(before: .distantFuture, now: Self.morning) == 3)
+ #expect(try await store.health(for: Fixtures.reportID(1))?.isSettled == false)
+ #expect(try await store.health(for: Fixtures.reportID(2))?.isSettled == true)
+
+ let later = Self.morning.addingTimeInterval(3600)
+ #expect(try await fill(reader).fill(before: .distantFuture, now: later) == 1)
+ #expect(try await store.health(for: Fixtures.reportID(1))?.derivedAt == later)
+ }
+
+ @Test("A pass covers only the reports in its range")
+ func ranges() async throws {
+ let reader = FakeHealthReader()
+ let since = Self.morning.addingTimeInterval(-10 * 3600)
+ for (number, hours) in [(1, 1.0), (2, 5.0), (3, 20.0), (4, 40.0), (5, 60.0)] {
+ try await store.insert(Self.report(number, hoursAgo: hours))
+ }
+ #expect(try await fill(reader).fill(since: since, before: .distantFuture, now: Self.morning) == 2)
+ #expect(try await store.health(for: Fixtures.reportID(3)) == nil)
+ #expect(try await fill(reader).fill(before: since, now: Self.morning) == 3)
+ #expect(try await store.health(for: Fixtures.reportID(5)) != nil)
+ }
+
+ @Test("Health entries go with their reports")
+ func deletion() async throws {
+ let reader = FakeHealthReader()
+ try await store.insert(Self.report(1, hoursAgo: 30))
+ try await store.insert(Self.report(2, hoursAgo: 40))
+ try await fill(reader).fill(before: .distantFuture, now: Self.morning)
+ try await store.delete(id: Fixtures.reportID(1))
+ #expect(try await healthCount() == 1)
+ try await store.deleteAll()
+ #expect(try await healthCount() == 0)
+ }
+
+ private func healthCount() async throws -> Int {
+ let context = persistence.newBackgroundContext()
+ return try await context.perform {
+ try context.count(for: HealthEntity.fetchRequest())
+ }
+ }
+}
diff --git a/Tests/Unit/ReportDetailsTests.swift b/Tests/Unit/ReportDetailsTests.swift
@@ -135,4 +135,24 @@ struct ReportDetailsTests {
#expect(Self.value("Average Level", in: "Sound", of: details) == "42.5 dB")
#expect(Self.value("Taken Since Last Report", in: "Photos", of: details) == "2")
}
+
+ @Test("Health from the cache appears after Sound, and missing values are left out")
+ func health() throws {
+ let health = HealthContext(
+ activity: ActivityHealth(steps: 4321, distance: 3200),
+ sleep: SleepHealth(
+ start: Self.date.addingTimeInterval(-8 * 3600), end: Self.date.addingTimeInterval(-3600),
+ asleep: 6.5 * 3600))
+ let context = Context(audio: AudioContext(source: .microphone, average: 40))
+ let details = ReportDetails(
+ report: Self.report(context: context), health: health, lookup: SummaryLookup(), locale: Self.locale)
+
+ #expect(details.sections.map(\.title) == ["Time", "Sound", "Health", "Record"])
+ #expect(Self.value("Steps Today", in: "Health", of: details) == "4,321")
+ #expect(Self.value("Distance Today", in: "Health", of: details) == "3.2 km")
+ #expect(Self.value("Flights Climbed Today", in: "Health", of: details) == nil)
+ let asleep = try #require(Self.value("Time Asleep", in: "Health", of: details))
+ #expect(asleep.hasPrefix("6 hr") && asleep.contains("30 min"))
+ #expect(Self.value("Deep Sleep", in: "Health", of: details) == nil)
+ }
}
diff --git a/Tests/Unit/SchemaMigrationTests.swift b/Tests/Unit/SchemaMigrationTests.swift
@@ -15,11 +15,13 @@ struct SchemaMigrationTests {
PersistenceController(inMemory: true).container.managedObjectModel
}
- /// The model as it was while reports had narrative attributes. Its
- /// entities use plain managed objects, so it doesn't claim the app's
- /// entity classes.
+ /// The model as it was while reports had narrative attributes, before
+ /// the Health cache. Its entities use plain managed objects, so it
+ /// doesn't claim the app's entity classes.
private static func narrativeModel() -> NSManagedObjectModel {
let copy = model.copy() as! NSManagedObjectModel
+ copy.entities.removeAll { $0.name == "HealthEntity" }
+ copy.entitiesByName["ReportEntity"]?.properties.removeAll { $0.name == "health" }
for entity in copy.entities {
entity.managedObjectClassName = NSStringFromClass(NSManagedObject.self)
}
diff --git a/project.yml b/project.yml
@@ -40,6 +40,7 @@ targets:
LSRequiresIPhoneOS: true
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.
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: {}