-1

I am trying to make my app show the total of steps I have done today. According to by Health-Kit app on my phone I have done 6 steps, but the app tells me 0. This is the full code I am using:

import UIKit
import HealthKit

class ViewController: UIViewController {

    @IBOutlet weak var stepsLabel: UILabel!

    let healthStore = HKHealthStore()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        getTodaysSteps { (count) in
            DispatchQueue.main.async {
                self.stepsLabel.text = count.description
                print("DONE: \(count)")
            }
        }

    }

    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, _ in
            guard let result = result, let sum = result.sumQuantity() else {
                completion(0.0)
                return
            }
            completion(sum.doubleValue(for: HKUnit.count()))
        }

        healthStore.execute(query)
    }
}

Is there anything I have missed here? Code from: https://stackoverflow.com/a/44111542/10660554

rmaddy
  • 314,917
  • 42
  • 532
  • 579

1 Answers1

-1

Have you tried this solution?

func retrieveStepCount(completion: @escaping (_ stepRetrieved: Double) -> Void) {

    //   Define the Step Quantity Type
    let stepsCount = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)

    //   Get the start of the day
    let date = Date()
    let cal = Calendar(identifier: Calendar.Identifier.gregorian)
    let newDate = cal.startOfDay(for: date)

    //  Set the Predicates & Interval
    let predicate = HKQuery.predicateForSamples(withStart: newDate, end: Date(), options: .strictStartDate)
    var interval = DateComponents()
    interval.day = 1

    //  Perform the Query
    let query = HKStatisticsCollectionQuery(quantityType: stepsCount!, quantitySamplePredicate: predicate, options: [.cumulativeSum], anchorDate: newDate as Date, intervalComponents:interval)

    query.initialResultsHandler = { query, results, error in

        if error != nil {

            //  Something went Wrong
            return
        }

        if let myResults = results{

            let now = Date()

            myResults.enumerateStatistics(from: newDate, to: now, with: { (statistics, stop) in

                if let quantity = statistics.sumQuantity() {

                    let steps = quantity.doubleValue(for: HKUnit.count())

                    print("Steps = \(steps)")
                    completion(steps)

                }
            })
        }


    }

    healthStore.execute(query)
}

Code from: https://stackoverflow.com/a/38697061/3420996

Natarajan
  • 3,241
  • 3
  • 17
  • 34
  • You know how can I get step history also? – Connor Sidne Dec 01 '18 at 01:19
  • I believe, you can also get the steps history by using the start date, here "newDate" is start date. If you change it to 5 days older, you can get the history of steps for fives. – Natarajan Dec 01 '18 at 01:34