我试图从过去的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)
    }

最佳答案

尝试使用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())
                // ...
            }
        }
    }

关于ios - 如何获取最近7天的健康数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49210818/

10-11 14:36