Swift 怎么查某段时间的 HealthKit 睡眠数据来源

时间:2026-12-01

浏览:113

作者:佚名

为 HealthKit 的睡眠样本加上时间过滤,再查询写入这些样本的来源。结果仅覆盖当前应用能读取的匹配数据。

HealthKit 官方地址 https://developer.apple.com/documentation/healthkit

1. 为睡眠样本申请读取权限

给 iOS 应用添加 HealthKit 能力,在应用配置中填写 NSHealthShareUsageDescription。在读取前检查设备支持 HealthKit,并用 requestAuthorization(toShare:read:) 请求读取 .sleepAnalysis。只读取记录时,写入权限可以留空。

2. 先限定时间,再取写入来源

假设应用 A 有一条 01:00–02:00 的可读睡眠样本,应用 B 只有一条 09:00–10:00 的样本。查询同一天的 00:00–08:00 时,应用 A 符合时间条件,应用 B 超出时间范围。如果可见样本只有这两条,查询就只返回应用 A。

查询 00:00 到 08:00 时,应用 A 的样本匹配,应用 B 的样本超出时段
来源匹配示意图(原创绘制)。仅在查询时段有匹配样本的应用 A 被返回。

下面的函数用于 iOS 15.4 及以上版本,在请求过读取权限后调用。start 与 end 由调用方按用户所选时段构造。查询选项留空可以纳入跨越边界、与该时段重叠的样本,例如前一晚开始而在凌晨结束的记录。

import Foundation
import HealthKit

enum SleepSourceError: Error {
    case invalidInterval
    case healthDataUnavailable
}

@available(iOS 15.4, *)
func sleepSources(
    store: HKHealthStore,
    start: Date,
    end: Date
) async throws -> [HKSource] {
    guard start < end else {
        throw SleepSourceError.invalidInterval
    }
    guard HKHealthStore.isHealthDataAvailable(),
          let sleep = HKObjectType.categoryType(forIdentifier: .sleepAnalysis) else {
        throw SleepSourceError.healthDataUnavailable
    }

    // 保留和查询时段重叠的睡眠样本,再查这些样本的写入来源。
    let period = HKQuery.predicateForSamples(withStart: start, end: end, options: [])
    let predicate = HKSamplePredicate.categorySample(type: sleep, predicate: period)
    let query = HKSourceQueryDescriptor(predicate: predicate)
    return try await query.result(for: store)
}

3. 按标识核对来源与空结果

返回值是一次查询得到的 HKSource 列表。可以展示 name,并用 bundleIdentifier 区分名称相同的来源。如果需要查看某条记录的起止时间,还要另查匹配的睡眠样本。

列表为空时,可以提示这个时段没有读到匹配记录,再检查日期范围。HealthKit 不向应用直接公开用户是否允许读取,因此空列表无法区分没有记录和记录对当前应用不可见。

本文内容来源于互联网,如有侵权请联系删除。

相关文章

更多

热门专题

更多
首页