AppleHealthTestView.swift
9.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
//
// AppleHealthTestView.swift
// Runner
//
// Created by 权海 on 2026/6/15.
//
import SwiftUI
struct AppleHealthTestView: View {
@State private var logs: [String] = []
@State private var isRunning = false
@State private var runningTitle: String?
private let api = HealthKitHostApiImpl()
private let logTimeFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm:ss.SSS"
return formatter
}()
var body: some View {
NavigationStack {
VStack(spacing: 0) {
logPanel
Divider()
HStack(spacing: 12) {
actionButton(title: "AppleHealth 权限检查", systemImage: "checkmark.shield") {
await runPermissionCheck()
}
actionButton(title: "获取数据接口", systemImage: "waveform.path.ecg") {
await runDataFetch()
}
}
.padding(16)
.background(.regularMaterial)
}
.navigationTitle("Apple Health Test")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .topBarTrailing) {
Button("清空") {
logs.removeAll()
}
.disabled(isRunning || logs.isEmpty)
}
}
}
}
private var logPanel: some View {
ScrollViewReader { proxy in
ScrollView {
LazyVStack(alignment: .leading, spacing: 8) {
if logs.isEmpty {
ContentUnavailableView(
"暂无日志",
systemImage: "list.bullet.rectangle",
description: Text("点击底部按钮开始测试 HealthKitHostApiImpl。")
)
.frame(maxWidth: .infinity, minHeight: 280)
} else {
ForEach(Array(logs.enumerated()), id: \.offset) { index, line in
Text(line)
.font(.system(.footnote, design: .monospaced))
.foregroundStyle(line.contains("❌") ? .red : .primary)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
.id(index)
}
}
}
.padding(16)
}
.background(Color(.systemGroupedBackground))
.onChange(of: logs.count) { _, newValue in
guard newValue > 0 else { return }
withAnimation(.easeOut(duration: 0.2)) {
proxy.scrollTo(newValue - 1, anchor: .bottom)
}
}
}
}
private func actionButton(
title: String,
systemImage: String,
action: @escaping () async -> Void
) -> some View {
Button {
guard !isRunning else { return }
Task {
await runAction(title, action: action)
}
} label: {
Label(isRunning && runningTitle == title ? "执行中..." : title, systemImage: systemImage)
.font(.system(size: 15, weight: .semibold))
.frame(maxWidth: .infinity)
.frame(height: 48)
}
.buttonStyle(.borderedProminent)
.disabled(isRunning)
}
@MainActor
private func runAction(_ title: String, action: @escaping () async -> Void) async {
isRunning = true
runningTitle = title
appendLog("▶️ \(title) 开始")
await action()
appendLog("✅ \(title) 完成")
isRunning = false
runningTitle = nil
}
private func runPermissionCheck() async {
do {
let isAuthorized = try await checkHealthAuthorization()
await appendLog("checkHealthAppAuthorization = \(isAuthorized)")
let authUrl = try await getHealthServerAuthUrl()
await appendLog("getHealthServerAuthUrl = \(authUrl.isEmpty ? "<empty, iOS system managed>" : authUrl)")
if !isAuthorized {
await appendLog("当前未授权,开始 requestHealthClientAuthorization")
let granted = try api.requestHealthClientAuthorization()
await appendLog("requestHealthClientAuthorization = \(granted)")
} else {
await appendLog("当前已授权,跳过 requestHealthClientAuthorization")
}
let cancelResult = try api.cancelHealthAppAuthorization()
await appendLog("cancelHealthAppAuthorization = \(cancelResult) (iOS 不支持应用内撤销)")
} catch {
await appendError("权限检查失败", error)
}
}
private func runDataFetch() async {
let endTime = Int64(Date().timeIntervalSince1970)
let startTime = Int64(Calendar.current.date(byAdding: .day, value: -7, to: Date())?.timeIntervalSince1970 ?? Date().timeIntervalSince1970)
await appendLog("数据范围: \(formatTimestamp(startTime)) -> \(formatTimestamp(endTime))")
do {
let uploadResult = try api.performHealthUpload()
await appendLog(
"performHealthUpload common=\(uploadResult.commonUploadSuccess), sleep=\(uploadResult.sleepUploadSuccess), error=\(uploadResult.errorMessage ?? "nil")"
)
} catch {
await appendError("performHealthUpload 失败", error)
}
await fetchCommon("HRV", startTime, endTime, api.fetchHrvData)
await fetchCommon("心率", startTime, endTime, api.fetchHeartRateData)
await fetchCommon("步行心率", startTime, endTime, api.fetchWalkingHeartRateData)
await fetchCommon("静息心率", startTime, endTime, api.fetchRestingHeartRateData)
await fetchCommon("睡眠心率", startTime, endTime, api.fetchSleepingHeartRateData)
await fetchCommon("血氧", startTime, endTime, api.fetchOxygenSaturationData)
await fetchCommon("活动能量", startTime, endTime, api.fetchActiveEnergyData)
await fetchCommon("锻炼", startTime, endTime, api.fetchExerciseData)
await fetchCommon("站立", startTime, endTime, api.fetchStandData)
await fetchCommon("步数", startTime, endTime, api.fetchStepCountData)
await fetchCommon("睡眠腕温", startTime, endTime, api.fetchSleepingWristTemperatureData)
await fetchCommon("呼吸频率", startTime, endTime, api.fetchRespiratoryRateData)
await fetchCommon("不规则心律", startTime, endTime, api.fetchIrregularHeartRhythmData)
await fetchSleep(startTime: startTime, endTime: endTime)
await fetchActivityTarget(startTime: startTime, endTime: endTime)
}
private func fetchCommon(
_ title: String,
_ startTime: Int64,
_ endTime: Int64,
_ fetch: @escaping (Int64, Int64, @escaping (Result<[HealthUploadDataPoint], Error>) -> Void) -> Void
) async {
do {
let points = try await withCheckedThrowingContinuation { continuation in
fetch(startTime, endTime) { result in
continuation.resume(with: result)
}
}
await appendLog("\(title): \(points.count) 条")
await appendSample(points)
} catch {
await appendError("\(title) 获取失败", error)
}
}
private func fetchSleep(startTime: Int64, endTime: Int64) async {
do {
let points = try await withCheckedThrowingContinuation { continuation in
api.fetchSleepData(startTime: startTime, endTime: endTime) { result in
continuation.resume(with: result)
}
}
await appendLog("睡眠: \(points.count) 条")
for point in points.prefix(3) {
await appendLog(" sample dataType=\(point.dataType), from=\(formatTimestamp(point.fromTime)), to=\(formatTimestamp(point.toTime))")
}
} catch {
await appendError("睡眠获取失败", error)
}
}
private func fetchActivityTarget(startTime: Int64, endTime: Int64) async {
do {
let target = try await withCheckedThrowingContinuation { continuation in
api.fetchActivityTargetData(startTime: startTime, endTime: endTime) { result in
continuation.resume(with: result)
}
}
if let target {
await appendLog("活动目标: move=\(target.move.map(String.init) ?? "nil"), stand=\(target.stand.map(String.init) ?? "nil")")
} else {
await appendLog("活动目标: nil")
}
} catch {
await appendError("活动目标获取失败", error)
}
}
private func checkHealthAuthorization() async throws -> Bool {
try await withCheckedThrowingContinuation { continuation in
api.checkHealthAppAuthorization { result in
continuation.resume(with: result)
}
}
}
private func getHealthServerAuthUrl() async throws -> String {
try await withCheckedThrowingContinuation { continuation in
api.getHealthServerAuthUrl { result in
continuation.resume(with: result)
}
}
}
@MainActor
private func appendLog(_ message: String) {
logs.append("[\(logTimeFormatter.string(from: Date()))] \(message)")
}
@MainActor
private func appendError(_ prefix: String, _ error: Error) {
appendLog("❌ \(prefix): \(error.localizedDescription)")
}
@MainActor
private func appendSample(_ points: [HealthUploadDataPoint]) {
for point in points.prefix(3) {
appendLog(" sample dataType=\(point.dataType), time=\(formatTimestamp(point.time)), value=\(point.value)")
}
}
private func formatTimestamp(_ timestamp: Int64) -> String {
let date = Date(timeIntervalSince1970: TimeInterval(timestamp))
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return formatter.string(from: date)
}
}
#Preview {
AppleHealthTestView()
}