swift-health-kit
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseHealthKit
HealthKit
What to open
打开指引
- Use for complete HealthKit documentation (188 pages consolidated).
Articles/healtkit.md - Search within the file by section URLs or keywords like ,
HKHealthStore,HKQuantitySample,HKWorkout.HKObserverQuery
- 使用获取完整的HealthKit文档(整合了188页内容)。
Articles/healtkit.md - 可通过章节URL或关键词(如、
HKHealthStore、HKQuantitySample、HKWorkout)在文件内搜索。HKObserverQuery
Document structure
文档结构
The documentation file is organized by Apple documentation URLs as section headers. Key sections:
| Line | Topic |
|---|---|
| ~11 | Framework overview |
| ~115 | About the HealthKit framework (architecture) |
| ~246 | Setting up HealthKit (entitlements, Info.plist) |
| ~357 | Authorizing access to health data |
| ~517 | Protecting user privacy |
| ~586 | Saving data to HealthKit |
| ~673 | Reading data from HealthKit (queries) |
| ~760 | HKHealthStore API reference |
| ~968 | Creating a Mobility Health App (sample project) |
| ~1025 | Data types (type identifiers) |
| ~1614 | Samples (HKSample, quantity, category, correlations) |
| ~1871 | Queries (sample, anchored, statistics, observer) |
| ~2146 | Visualizing State of Mind in visionOS |
| ~2203 | Logging symptoms associated with a medication |
| ~2278 | Workouts and activity rings |
| ~2449 | HKError and error handling |
| ~3152 | Executing observer queries |
| ~4778 | Background delivery (HKUpdateFrequency) |
| ~5974 | HKObjectType and subclasses |
| ~7264 | HKSampleType reference |
该文档文件以Apple文档URL作为章节标题进行组织。关键章节如下:
| 行号 | 主题 |
|---|---|
| ~11 | 框架概述 |
| ~115 | HealthKit框架简介(架构) |
| ~246 | HealthKit配置(权限、Info.plist) |
| ~357 | 健康数据访问授权 |
| ~517 | 用户隐私保护 |
| ~586 | 向HealthKit保存数据 |
| ~673 | 从HealthKit读取数据(查询) |
| ~760 | HKHealthStore API参考 |
| ~968 | 开发移动健康应用(示例项目) |
| ~1025 | 数据类型(类型标识符) |
| ~1614 | 样本(HKSample、数值、分类、关联) |
| ~1871 | 查询(样本、锚定、统计、观察者) |
| ~2146 | 在visionOS中可视化心理状态 |
| ~2203 | 记录与药物相关的症状 |
| ~2278 | 运动与活动圆环 |
| ~2449 | HKError与错误处理 |
| ~3152 | 执行观察者查询 |
| ~4778 | 后台数据推送(HKUpdateFrequency) |
| ~5974 | HKObjectType及其子类 |
| ~7264 | HKSampleType参考 |
Setup checklist
配置检查清单
- Add HealthKit capability in Xcode (enable Clinical Health Records only if needed).
- Add and
NSHealthShareUsageDescriptionto Info.plist.NSHealthUpdateUsageDescription - Check before any HealthKit calls.
HKHealthStore.isHealthDataAvailable() - Create a single instance and retain it for the app's lifetime.
HKHealthStore - Request authorization with before reading or writing.
requestAuthorization(toShare:read:)
- 在Xcode中添加HealthKit功能(仅在需要时启用临床健康记录)。
- 向Info.plist中添加和
NSHealthShareUsageDescription字段。NSHealthUpdateUsageDescription - 在调用任何HealthKit接口前,检查。
HKHealthStore.isHealthDataAvailable() - 创建单个实例,并在应用生命周期内保持引用。
HKHealthStore - 在读写数据前,调用请求授权。
requestAuthorization(toShare:read:)
Common workflows
常见工作流
Reading data
读取数据
- Create the appropriate or
HKSampleType.HKQuantityType - Build a query descriptor (e.g., ,
HKSampleQueryDescriptor).HKStatisticsQueryDescriptor - Execute the query against .
HKHealthStore - Handle results on a background queue; dispatch to main for UI updates.
- 创建对应的或
HKSampleType。HKQuantityType - 构建查询描述符(如、
HKSampleQueryDescriptor)。HKStatisticsQueryDescriptor - 在上执行查询。
HKHealthStore - 在后台队列处理结果;如需更新UI,调度至主线程。
Saving data
保存数据
- Create an ,
HKQuantitySample, orHKCategorySample.HKCorrelation - Use matching units for the data type (e.g., for steps,
.count()for distance)..meter() - Call .
healthStore.save(_:withCompletion:) - Check before saving to catch permission issues early.
authorizationStatus(for:)
- 创建、
HKQuantitySample或HKCategorySample实例。HKCorrelation - 为数据类型使用匹配的单位(如步数使用,距离使用
.count())。.meter() - 调用。
healthStore.save(_:withCompletion:) - 保存前调用检查权限,提前发现权限问题。
authorizationStatus(for:)
Background delivery
后台数据推送
- Enable Background Modes in Xcode (Background fetch).
- Call for each data type.
enableBackgroundDelivery(for:frequency:withCompletion:) - Register an with an update handler.
HKObserverQuery - When woken, call to re-run the query.
healthStore.execute(_:)
- 在Xcode中启用后台模式(后台获取)。
- 为每个数据类型调用。
enableBackgroundDelivery(for:frequency:withCompletion:) - 注册带有更新处理程序的。
HKObserverQuery - 应用被唤醒时,调用重新执行查询。
healthStore.execute(_:)
Workouts
运动功能
- Create an with activity type and location.
HKWorkoutConfiguration - Start a workout session on Apple Watch with .
HKWorkoutSession - Use to collect real-time samples.
HKLiveWorkoutBuilder - End the session and save the workout with .
endCollection(withEnd:completion:)
- 创建包含活动类型和位置信息的。
HKWorkoutConfiguration - 在Apple Watch上使用启动运动会话。
HKWorkoutSession - 使用收集实时样本数据。
HKLiveWorkoutBuilder - 结束会话并调用保存运动记录。
endCollection(withEnd:completion:)
Key types
核心类型
| Type | Purpose |
|---|---|
| Central access point; authorization, queries, saving |
| Numeric health data (steps, heart rate, weight) |
| Enumerated data (sleep analysis, menstrual flow) |
| Composite samples (food, blood pressure) |
| Fitness activity with duration, energy, distance |
| Long-running query for store changes |
| Track additions/deletions since last anchor |
| Aggregate calculations (sum, avg, min, max) |
| Time-bucketed statistics for charts |
| 类型 | 用途 |
|---|---|
| 核心访问入口;负责授权、查询、数据保存 |
| 数值型健康数据(步数、心率、体重) |
| 枚举型数据(睡眠分析、经期流量) |
| 复合样本(食物、血压) |
| 包含时长、消耗、距离的健身活动记录 |
| 用于监听存储变更的长期查询 |
| 跟踪自上次锚点以来的增删数据 |
| 聚合计算(求和、平均、最小、最大) |
| 按时间分段的统计数据,用于图表展示 |
Privacy and authorization
隐私与授权
- HealthKit uses fine-grained authorization per data type.
- Apps cannot detect if read permission was denied; queries simply return no data.
- Use to check write permission before saving.
authorizationStatus(for:) - Guest User sessions on visionOS restrict mutations; handle .
errorNotPermissibleForGuestUserMode - Never use HealthKit data for advertising or sell it to third parties.
- HealthKit针对每个数据类型使用细粒度授权。
- 应用无法检测读取权限是否被拒绝;查询仅会返回空数据。
- 保存前使用检查写入权限。
authorizationStatus(for:) - visionOS的访客用户会话限制数据修改;需处理错误。
errorNotPermissibleForGuestUserMode - 绝不能将HealthKit数据用于广告或出售给第三方。
Platform availability
平台兼容性
- iPhone/Apple Watch/visionOS: Full HealthKit store with sync.
- iPadOS 17+: Has its own HealthKit store.
- iPadOS 16 and earlier / macOS 13+: Framework available but returns
isHealthDataAvailable().false - Use on Apple Watch to find oldest available data.
earliestPermittedSampleDate()
- iPhone/Apple Watch/visionOS: 完整的HealthKit存储,支持同步。
- iPadOS 17+: 拥有独立的HealthKit存储。
- iPadOS 16及更早版本 / macOS 13+: 框架可用,但返回
isHealthDataAvailable()。false - 在Apple Watch上使用查找最早可用数据。
earliestPermittedSampleDate()
Error handling
错误处理
Check for these common values:
HKError.Code- – Device doesn't support HealthKit.
errorHealthDataUnavailable - – Enterprise or parental restrictions.
errorHealthDataRestricted - – Authorization not yet requested.
errorAuthorizationNotDetermined - – User denied write permission.
errorAuthorizationDenied - – Vision Pro guest session restriction.
errorNotPermissibleForGuestUserMode - – Required clinical record types denied.
errorRequiredAuthorizationDenied
需注意以下常见错误码:
HKError.Code- – 设备不支持HealthKit。
errorHealthDataUnavailable - – 受企业或家长限制。
errorHealthDataRestricted - – 尚未请求授权。
errorAuthorizationNotDetermined - – 用户拒绝写入权限。
errorAuthorizationDenied - – Vision Pro访客会话限制。
errorNotPermissibleForGuestUserMode - – 必需的临床记录类型权限被拒绝。
errorRequiredAuthorizationDenied
SwiftUI integration
SwiftUI集成
Use the framework for SwiftUI authorization:
HealthKitUIswift
import HealthKitUI
.healthDataAccessRequest(
store: healthStore,
shareTypes: allTypes,
readTypes: allTypes,
trigger: trigger
) { result in
// Handle authorization result
}使用框架实现SwiftUI授权:
HealthKitUIswift
import HealthKitUI
.healthDataAccessRequest(
store: healthStore,
shareTypes: allTypes,
readTypes: allTypes,
trigger: trigger
) { result in
// Handle authorization result
}Reminders
注意事项
- HealthKit store is thread-safe; samples are immutable.
- Avoid samples longer than 24 hours; many types have duration limits.
- Correlations store contained samples internally—don't save them separately.
- Use via anchored queries to detect deletions.
HKDeletedObject - For workout heart rate zones, use and route samples.
HKWorkoutActivity
- HealthKit存储是线程安全的;样本数据不可变。
- 避免创建时长超过24小时的样本;许多数据类型有持续时间限制。
- 关联样本会在内部存储包含的样本——请勿单独保存这些样本。
- 通过锚定查询使用检测数据删除操作。
HKDeletedObject - 如需实现运动心率区间,使用和路线样本。
HKWorkoutActivity