如何获取最近 7 天的健康数据

How to obtain Health data from the last 7 days

我正在尝试获取过去 7 天的步数,但找不到具体操作方法。 我想要接收的是一个包含 7 个元素的数组,其中每个元素都是一天,其各自的总步数。我目前有这段代码,得到今天的步骤:

//Gets the steps
func getTodaysSteps(completion: @escaping (Double) -> Void) {
    let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!

    let now = Date()
    let startOfDay = Calendar.current.startOfDay(for: now)
    let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now, options: .strictStartDate)

    let query = HKStatisticsQuery(quantityType: stepsQuantityType, quantitySamplePredicate: predicate, options: .cumulativeSum) { (_, result, error) in
        guard let result = result, let sum = result.sumQuantity() else {
            print("Failed to fetch steps = \(error?.localizedDescription ?? "N/A")")
            completion(0.0)
            return
        }

        DispatchQueue.main.async {
            completion(sum.doubleValue(for: HKUnit.count()))
        }
    }
    healthKitStore.execute(query)
}

我这样调用函数:

getTodaysSteps { (steps) in
        self.stepsNumber = Int(steps)
    }

您必须实施的唯一更改是将您作为 startWith 参数提供的 Date 对象更改为您的 HKStatisticsQuery。您可以创建一个表示 7 天前一天开始的 Date 对象,方法是首先使用 Calendar.date(byAdding:,to:) 恰好返回 7 天的时间,然后对该对象调用 startOfDay(for:)

let now = Date()
let exactlySevenDaysAgo = Calendar.current.date(byAdding: DateComponents(day: -7), to: now)!
let startOfSevenDaysAgo = Calendar.current.startOfDay(for: exactlySevenDaysAgo)
let predicate = HKQuery.predicateForSamples(withStart: startOfSevenDaysAgo, end: now, options: .strictStartDate)

尝试使用 HKStatisticsCollectionQuery,它将为您计算日期并自动存储结果。下面是一个应提供过去 7 天步数的示例:

    let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!

    let now = Date()
    let exactlySevenDaysAgo = Calendar.current.date(byAdding: DateComponents(day: -7), to: now)!
    let startOfSevenDaysAgo = Calendar.current.startOfDay(for: exactlySevenDaysAgo)
    let predicate = HKQuery.predicateForSamples(withStart: startOfSevenDaysAgo, end: now, options: .strictStartDate)

    let query = HKStatisticsCollectionQuery.init(quantityType: stepsQuantityType,
                                                 quantitySamplePredicate: predicate,
                                                 options: .cumulativeSum,
                                                 anchorDate: startOfSevenDaysAgo,
                                                 intervalComponents: DateComponents(day: 1))

    query.initialResultsHandler = { query, results, error in
        guard let statsCollection = results else {
            // Perform proper error handling here...
        }

        statsCollection.enumerateStatistics(from: startOfSevenDaysAgo, to: now) { statistics, stop in

            if let quantity = statistics.sumQuantity() {
                let stepValue = quantity.doubleValueForUnit(HKUnit.countUnit())
                // ...
            }
        }
    }

这里有更简单的解决方案。

func getTotalSteps(forPast days: Int, completion: @escaping (Double) -> Void) {
    // Getting quantityType as stepCount
    guard let stepsQuantityType = HKObjectType.quantityType(forIdentifier: .stepCount) else {
        print("*** Unable to create a step count type ***")
        return
    }

    let now = Date()
    let startDate = Calendar.current.date(byAdding: DateComponents(day: -days), to: now)
    let predicate = HKQuery.predicateForSamples(withStart: startDate, end: now, options: .strictStartDate)

    let query = HKStatisticsQuery(quantityType: stepsQuantityType, quantitySamplePredicate: predicate, options: .cumulativeSum) { _, result, _ in
        guard let result = result, let sum = result.sumQuantity() else {
            completion(0.0)
            return
        }
        completion(sum.doubleValue(for: HKUnit.count()))
    }
    execute(query)
}

现在调用只需使用以下代码:

HKHealthStore().getTotalSteps(forPast: 30) { totalSteps in
    print(totalSteps)
}