0

我正在尝试获取过去 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)
    }
4

3 回答 3

5

尝试使用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())
                // ...
            }
        }
    }
于 2018-03-12T16:48:38.153 回答
3

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

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)
}
于 2019-04-12T15:57:10.083 回答
0

您必须实现的唯一更改是将作为参数Date提供的对象更改为. 您可以创建一个表示 7 天前一天开始的对象,方法是首先使用 准确返回 7 天,然后调用该对象。startWithHKStatisticsQueryDateCalendar.date(byAdding:,to:)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)
于 2018-03-10T15:47:53.080 回答