Ryan
Ryan

Reputation: 682

HKStatisticsCollectionQuery works for one day and then stops. How to keep update handler working indefinitely?

The goal of this code is to monitor the users active calories burned each day. Right now the code works perfectly on day 1. The users calories burned on that day are fetched and the calorie count updates throughout the day. However, the next day the code stops working and it just displayed the users active calories burned on day 1. How can this code be fixed so that the update handler continues to fetch the users active calories burned every day without stopping at the end of the first day.

    func getSteps() -> Void {

    guard let energyBurnedType = HKObjectType.quantityType(forIdentifier: .activeEnergyBurned) else {
        fatalError("*** Unable to get the step count type ***")
    }

    var interval = DateComponents()
    interval.hour = 24

    let calendar = Calendar.current

    let anchorDate = calendar.date(bySettingHour: 0, minute: 0, second: 0, of: Date())

    let query = HKStatisticsCollectionQuery.init(quantityType: energyBurnedType,
                                              quantitySamplePredicate: nil,
                                              options: .cumulativeSum,
                                              anchorDate: anchorDate!,
                                              intervalComponents: interval)

    query.initialResultsHandler = {
     query, results, error in

    DispatchQueue.main.async {
        let startDate = calendar.startOfDay(for: Date())
        results?.enumerateStatistics(from: startDate,
                                  to: Date(), with: { (result, false) in
                                    self.moveResult = (Int(result.sumQuantity()?.doubleValue(for: HKUnit.kilocalorie()) ?? 0))})
    }
 }

query.statisticsUpdateHandler = {
    query, statistics, results, error in

    print("update handler set")
    DispatchQueue.main.async {

        // in order to fix problem of steps not updating at the start of new day I tried using Calendar.current
        let currentDay = Calendar.current
        let startDate = currentDay.startOfDay(for: Date())
        results?.enumerateStatistics(from: startDate,
                                     to: Date(), with: { (result, false) in
    self.moveResult = (Int(result.sumQuantity()?.doubleValue(for: HKUnit.kilocalorie()) ?? 0))})
    }
}


 healthStore.execute(query)}}

Upvotes: 3

Views: 1136

Answers (1)

Maks
Maks

Reputation: 322

Here is the problem:

let startDate = currentDay.startOfDay(for: Date())

Start date should not be today date.

Try to make this date few days before today.

For example:

Setup startDate to be 3 days before today

query.initialResultsHandler = {
 query, results, error in

DispatchQueue.main.async {
    let startDate = Calendar.current.date(byAdding: .day, value: -3, to: Date())
    results?.enumerateStatistics(from: startDate,
                              to: Date(), with: { (result, false) in
                                self.moveResult = (Int(result.sumQuantity()?.doubleValue(for: HKUnit.kilocalorie()) ?? 0))})
}

Upvotes: 2

Related Questions