Search code examples
iosswiftios10healthkit

Trying to get steps using HealthKit but it's always returning 0.0


I'm trying to get steps from half an hour ago and I'm using the method discussed here. The following is my code:

func getSteps(completion: @escaping (Double) -> Void) {
    let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!

    let now = Date()
    let calendar = Calendar.current
    let halfHourAgoDate = calendar.date(byAdding: .minute, value: -30, to: now)

    if let date = halfHourAgoDate {
        let predicate = HKQuery.predicateForSamples(withStart: date, end: now, options: .strictStartDate)

        let query = HKStatisticsQuery(quantityType: stepsQuantityType, quantitySamplePredicate: predicate, options: .cumulativeSum) { (_, result, error) in
            var resultCount = 0.0

            guard let result = result else {
                completion(resultCount)
                return
            }

            if let sum = result.sumQuantity() {
                resultCount = sum.doubleValue(for: HKUnit.count())
                return
            }

            DispatchQueue.main.async {
                completion(resultCount)
            }
        }

        healthStore.execute(query)

    } else {
        print("Error MainVC, date is being cast as nil")
    }
}

When I actually try to get steps, this is my code:

 var todaysSteps: Double = 0
 getSteps(completion: { (resultCount) -> Void in
                                todaysSteps = resultCount
                            })
 print(todaysSteps) // always comes out to 0.0

Yet whenever I run this code, the code returns 0.0. I've enabled HealthKit, and authorized it for steps, so I'm not sure what the reason is. Also note this is in my variable declarations:

let healthStore = HKHealthStore()

Solution

  • For anyone encountering the same issue, you need to do the code inside the completion handler, so:

    var todaysSteps: Double = 0
    getSteps(completion: { (resultCount) -> Void in
                                print(resultCount)
    })