Token导航 LogoToken导航TokenDH.com
开发需要联网github未标认证来源可访问许可证需确认审计通过

healthkithealthkit 搜索

Agent Skill

healthkit 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

27,192

周安装

1,072

GitHub Stars

535

下载量

8,536
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:healthkit(healthkit 搜索)
来源仓库:https://github.com/dpearson2699/swift-ios-skills
仓库路径:skills/healthkit
安装命令:
npx skills add https://github.com/dpearson2699/swift-ios-skills --skill healthkit
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/dpearson2699/swift-ios-skills --skill healthkit

简介

用于处理 GitHub 仓库、Issue 和 Pull Request 协作信息。

  • 适合围绕代码变更、仓库状态或协作事项进行整理。
  • 可结合项目上下文理解技术细节和开发流程。适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。
  • 使用前需确认权限和操作边界,避免越权访问。
  • healthkit 属于开发类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

HealthKit

Read and write health and fitness data from the Apple Health store. Covers authorization, queries, writing samples, background delivery, and workout sessions. Targets Swift 6.3 / iOS 26+.

Contents

Setup and Availability

Project Configuration

  1. Enable the HealthKit capability in Xcode (adds the entitlement)
  2. Add NSHealthShareUsageDescription (read) and NSHealthUpdateUsageDescription (write) to Info.plist
  3. For background delivery, enable the "Background Delivery" sub-capability

Availability Check

Always check availability before accessing HealthKit. iPad and some devices do not support it.

import HealthKit

let healthStore = HKHealthStore()

guard HKHealthStore.isHealthDataAvailable() else {
    // HealthKit not available on this device (e.g., iPad)
    return
}

Create a single HKHealthStore instance and reuse it throughout your app. It is thread-safe.

Authorization

Request only the types your app genuinely needs. App Review rejects apps that over-request.

func requestAuthorization() async throws {
    let typesToShare: Set<HKSampleType> = [
        HKQuantityType(.stepCount),
        HKQuantityType(.activeEnergyBurned)
    ]

    let typesToRead: Set<HKObjectType> = [
        HKQuantityType(.stepCount),
        HKQuantityType(.heartRate),
        HKQuantityType(.activeEnergyBurned),
        HKCharacteristicType(.dateOfBirth)
    ]

    try await healthStore.requestAuthorization(
        toShare: typesToShare,
        read: typesToRead
    )
}

Checking Authorization Status

The app can only determine if it has not yet requested authorization. If the user denied access, HealthKit returns empty results rather than an error -- this is a privacy design.

let status = healthStore.authorizationStatus(
    for: HKQuantityType(.stepCount)
)

switch status {
case .notDetermined:
    // Haven't requested yet -- safe to call requestAuthorization
    break
case .sharingAuthorized:
    // User granted write access
    break
case .sharingDenied:
    // User denied write access (read denial is indistinguishable from "no data")
    break
@unknown default:
    break
}

Reading Data: Sample Queries

Use HKSampleQueryDescriptor (async/await) for one-shot reads. Prefer descriptors over the older callback-based HKSampleQuery.

func fetchRecentHeartRates() async throws -> [HKQuantitySample] {
    let heartRateType = HKQuantityType(.heartRate)

    let descriptor = HKSampleQueryDescriptor(
        predicates: [.quantitySample(type: heartRateType)],
        sortDescriptors: [SortDescriptor(\.endDate, order: .reverse)],
        limit: 20
    )

    let results = try await descriptor.result(for: healthStore)
    return results
}

// Extracting values from samples:
for sample in results {
    let bpm = sample.quantity.doubleValue(
        for: HKUnit.count().unitDivided(by: .minute())
    )
    print("\(bpm) bpm at \(sample.endDate)")
}

Reading Data: Statistics Queries

Use HKStatisticsQueryDescriptor for aggregated single-value stats (sum, average, min, max).

func fetchTodayStepCount() async throws -> Double? {
    let calendar = Calendar.current
    let startOfDay = calendar.startOfDay(for: Date())
    let endOfDay = calendar.date(byAdding: .day, value: 1, to: startOfDay)!

    let predicate = HKQuery.predicateForSamples(
        withStart: startOfDay, end: endOfDay
    )
    let stepType = HKQuantityType(.stepCount)
    let samplePredicate = HKSamplePredicate.quantitySample(
        type: stepType, predicate: predicate
    )

    let query = HKStatisticsQueryDescriptor(
        predicate: samplePredicate,
        options: .cumulativeSum
    )

    let result = try await query.result(for: healthStore)
    return result?.sumQuantity()?.doubleValue(for: .count())
}

Options by data type:

  • Cumulative types (steps, calories): .cumulativeSum
  • Discrete types (heart rate, weight): .discreteAverage, .discreteMin, .discreteMax

Reading Data: Statistics Collection Queries

Use HKStatisticsCollectionQueryDescriptor for time-series data grouped into intervals -- ideal for charts.

func fetchDailySteps(forLast days: Int) async throws -> [(date: Date, steps: Double)] {
    let calendar = Calendar.current
    let endDate = calendar.startOfDay(
        for: calendar.date(byAdding: .day, value: 1, to: Date())!
    )
    let startDate = calendar.date(byAdding: .day, value: -days, to: endDate)!

    let predicate = HKQuery.predicateForSamples(
        withStart: startDate, end: endDate
    )
    let stepType = HKQuantityType(.stepCount)
    let samplePredicate = HKSamplePredicate.quantitySample(
        type: stepType, predicate: predicate
    )

    let query = HKStatisticsCollectionQueryDescriptor(
        predicate: samplePredicate,
        options: .cumulativeSum,
        anchorDate: endDate,
        intervalComponents: DateComponents(day: 1)
    )

    let collection = try await query.result(for: healthStore)
    var dailySteps: [(date: Date, steps: Double)] = []

    collection.statisticsCollection.enumerateStatistics(
        from: startDate, to: endDate
    ) { statistics, _ in
        let steps = statistics.sumQuantity()?
            .doubleValue(for: .count()) ?? 0
        dailySteps.append((date: statistics.startDate, steps: steps))
    }

    return dailySteps
}

Long-Running Collection Query

Use results(for:) (plural) to get an AsyncSequence that emits updates as new data arrives:

let updateStream = query.results(for: healthStore)

Task {
    for try await result in updateStream {
        // result.statisticsCollection contains updated data
    }
}

Writing Data

Create HKQuantitySample objects and save them to the store.

func saveSteps(count: Double, start: Date, end: Date) async throws {
    let stepType = HKQuantityType(.stepCount)
    let quantity = HKQuantity(unit: .count(), doubleValue: count)

    let sample = HKQuantitySample(
        type: stepType,
        quantity: quantity,
        start: start,
        end: end
    )

    try await healthStore.save(sample)
}

Your app can only delete samples it created. Samples from other apps or Apple Watch are read-only.

Background Delivery

Register for background updates so your app is launched when new data arrives. Requires the background delivery entitlement.

func enableStepCountBackgroundDelivery() async throws {
    let stepType = HKQuantityType(.stepCount)

    try await healthStore.enableBackgroundDelivery(
        for: stepType,
        frequency: .hourly
    )
}

Pair with an HKObserverQuery to handle notifications. Always call the completion handler:

let observerQuery = HKObserverQuery(
    sampleType: HKQuantityType(.stepCount),
    predicate: nil
) { query, completionHandler, error in
    defer { completionHandler() }  // Must call to signal done
    guard error == nil else { return }
    // Fetch new data, update UI, etc.
}
healthStore.execute(observerQuery)

Frequencies: .immediate, .hourly, .daily, .weekly

Call enableBackgroundDelivery once (e.g., at app launch). The system persists the registration.

Workout Sessions

Use HKWorkoutSession and HKLiveWorkoutBuilder to track live workouts. Available on watchOS 2+ and iOS 17+.

func startWorkout() async throws {
    let configuration = HKWorkoutConfiguration()
    configuration.activityType = .running
    configuration.locationType = .outdoor

    let session = try HKWorkoutSession(
        healthStore: healthStore,
        configuration: configuration
    )
    session.delegate = self

    let builder = session.associatedWorkoutBuilder()
    builder.dataSource = HKLiveWorkoutDataSource(
        healthStore: healthStore,
        workoutConfiguration: configuration
    )

    session.startActivity(with: Date())
    try await builder.beginCollection(at: Date())
}

func endWorkout(
    session: HKWorkoutSession,
    builder: HKLiveWorkoutBuilder
) async throws {
    session.end()
    try await builder.endCollection(at: Date())
    try await builder.finishWorkout()
}

For full workout lifecycle management including pause/resume, delegate handling, and multi-device mirroring, see references/healthkit-patterns.md.

Common Data Types

HKQuantityTypeIdentifier

IdentifierCategoryUnit
.stepCountFitness.count()
.distanceWalkingRunningFitness.meter()
.activeEnergyBurnedFitness.kilocalorie()
.basalEnergyBurnedFitness.kilocalorie()
.heartRateVitals.count()/.minute()
.restingHeartRateVitals.count()/.minute()
.oxygenSaturationVitals.percent()
.bodyMassBody.gramUnit(with:.kilo)
.bodyMassIndexBody.count()
.heightBody.meter()
.bodyFatPercentageBody.percent()
.bloodGlucoseLab.gramUnit(with:.milli).unitDivided(by:.literUnit(with:.deci))

HKCategoryTypeIdentifier

Common category types: .sleepAnalysis, .mindfulSession, .appleStandHour

HKCharacteristicType

Read-only user characteristics: .dateOfBirth, .biologicalSex, .bloodType, .fitzpatrickSkinType

HKUnit Reference

// Basic units
HKUnit.count()                              // Steps, counts
HKUnit.meter()                              // Distance
HKUnit.mile()                               // Distance (imperial)
HKUnit.kilocalorie()                        // Energy
HKUnit.joule(with: .kilo)                   // Energy (SI)
HKUnit.gramUnit(with: .kilo)                // Mass (kg)
HKUnit.pound()                              // Mass (imperial)
HKUnit.percent()                            // Percentage

// Compound units
HKUnit.count().unitDivided(by: .minute())   // Heart rate (bpm)
HKUnit.meter().unitDivided(by: .second())   // Speed (m/s)

// Prefixed units
HKUnit.gramUnit(with: .milli)               // Milligrams
HKUnit.literUnit(with: .deci)               // Deciliters

Common Mistakes

1. Over-requesting data types

DON'T -- request everything:

// App Review will reject this
let allTypes: Set<HKObjectType> = [
    HKQuantityType(.stepCount),
    HKQuantityType(.heartRate),
    HKQuantityType(.bloodGlucose),
    HKQuantityType(.bodyMass),
    HKQuantityType(.oxygenSaturation),
    // ...20 more types the app never uses
]

DO -- request only what you use:

let neededTypes: Set<HKObjectType> = [
    HKQuantityType(.stepCount),
    HKQuantityType(.activeEnergyBurned)
]

2. Not handling authorization denial

DON'T -- assume data will be returned:

func getSteps() async throws -> Double {
    let result = try await query.result(for: healthStore)
    return result!.sumQuantity()!.doubleValue(for: .count()) // Crashes if denied
}

DO -- handle nil gracefully:

func getSteps() async throws -> Double {
    let result = try await query.result(for: healthStore)
    return result?.sumQuantity()?.doubleValue(for: .count()) ?? 0
}

3. Assuming HealthKit is always available

DON'T -- skip the check:

let store = HKHealthStore() // Crashes on iPad
try await store.requestAuthorization(toShare: types, read: types)

DO -- guard availability:

guard HKHealthStore.isHealthDataAvailable() else {
    showUnsupportedDeviceMessage()
    return
}

4. Running heavy queries on the main thread

DON'T -- use old callback-based queries on main thread. DO -- use async descriptors:

// Bad: HKSampleQuery with callback on main thread
// Good: async descriptor
func loadAllData() async throws -> [HKQuantitySample] {
    let descriptor = HKSampleQueryDescriptor(
        predicates: [.quantitySample(type: stepType)],
        sortDescriptors: [SortDescriptor(\.endDate, order: .reverse)],
        limit: 100
    )
    return try await descriptor.result(for: healthStore)
}

5. Forgetting to call completionHandler in observer queries

DON'T -- skip the completion handler:

let query = HKObserverQuery(sampleType: type, predicate: nil) { _, handler, _ in
    processNewData()
    // Forgot to call handler() -- system won't schedule next delivery
}

DO -- always call it:

let query = HKObserverQuery(sampleType: type, predicate: nil) { _, handler, _ in
    defer { handler() }
    processNewData()
}

6. Using wrong statistics options for the data type

DON'T -- use cumulative sum on discrete types:

// Heart rate is discrete, not cumulative -- this returns nil
let query = HKStatisticsQueryDescriptor(
    predicate: heartRatePredicate,
    options: .cumulativeSum
)

DO -- match options to data type:

// Use discrete options for discrete types
let query = HKStatisticsQueryDescriptor(
    predicate: heartRatePredicate,
    options: .discreteAverage
)

Review Checklist

  • HKHealthStore.isHealthDataAvailable() checked before any HealthKit access
  • Only necessary data types requested in authorization
  • Info.plist includes NSHealthShareUsageDescription and/or NSHealthUpdateUsageDescription
  • HealthKit capability enabled in Xcode project
  • Authorization denial handled gracefully (nil results, not crashes)
  • Single HKHealthStore instance reused (not created per query)
  • Async query descriptors used instead of callback-based queries
  • Heavy queries not blocking main thread
  • Statistics options match data type (cumulative vs. discrete)
  • Background delivery paired with HKObserverQuery and completionHandler called
  • Background delivery entitlement enabled if using enableBackgroundDelivery
  • Workout sessions properly ended and builder finalized
  • Write operations only for sample types the app created

References

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

37.77%
按下载量换算3,224

Claude

28.34%
按下载量换算2,419

Cursor

16.79%
按下载量换算1,433

Gemini CLI

8.81%
按下载量换算752

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills