【问题标题】:How to access workouts from HealthKit on WatchOS?如何在 WatchOS 上通过 HealthKit 访问锻炼?
【发布时间】:2021-06-19 12:30:00
【问题描述】:

我正在尝试从 WatchOS 应用中读取锻炼数据。不幸的是,当我在 WatchOS 上阅读锻炼时,返回的锻炼总是空的。

这是目前的实现方式:

    func fetchWorkouts(limit: WorkoutLimit) async throws -> [HKWorkout] {
        let activityType = PulseConfiguration.activityType

        // 1. Get all workouts with the configured activity type.
        let walkingPredictate = HKQuery.predicateForWorkouts(with: activityType)

        // 2. Get all workouts that only came from this app.
        let sourcePredicate = HKQuery.predicateForObjects(from: .default())

        // 3. Combine the predicates into a single predicate.
        let compound = NSCompoundPredicate(andPredicateWithSubpredicates:
            [walkingPredictate, sourcePredicate])

        let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)

        typealias WorkoutsContinuation = CheckedContinuation<[HKWorkout], Error>
        return try await withCheckedThrowingContinuation { (continuation: WorkoutsContinuation) in
            let query = HKSampleQuery(
                sampleType: .workoutType(),
                predicate: compound,
                limit: limit.count,
                sortDescriptors: [sortDescriptor]
            ) { _, samples, error in
                guard let samples = samples as? [HKWorkout], error == nil else {
                    if let error = error {
                        continuation.resume(throwing: error)
                    }
                    return
                }
                continuation.resume(returning: samples)
            }
            healthStore.execute(query)
        }
    }

我注意到 .default (WatchOS) 返回的 HKSource 与保存的锻炼关联的源不同(其中包含来自 iPhone 应用程序的捆绑标识符)。 是否有其他方法可以从 WatchOS 应用程序访问锻炼?

提前致谢。乔什。

【问题讨论】:

    标签: healthkit watchos


    【解决方案1】:

    Watch 提供的健康数据子集有限。您可以使用HKHealthStore.earliestPermittedSampleDate 查看您可以查询多远的数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多