Search code examples
iosswiftxcodehealthkit

Cannot get today's steps to display into label


I am trying to create a label which displays today's steps from HealthKit. I have got as far as allowing HealthKit to read/write data, but I'm stuck on actually obtaining the data.

Can anyone offer any advice? Here's my code, including the label I want to display the steps:

import Foundation
import UIKit
import HealthKit


class HealthKitPage : UIViewController
{
      let healthStore: HKHealthStore = HKHealthStore()

      override func viewDidLoad()
      {
                var shareTypes = Set<HKSampleType>()

                shareTypes.insert(HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!)

                var readTypes = Set<HKObjectType>()
                readTypes.insert(HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!)


                healthStore.requestAuthorization(toShare: shareTypes, read: readTypes) { (success, error) -> Void in
                          if success {
                                    print("success")
                          } else {
                                    print("failure")
                          }

                          if let error = error { print(error) }


                }


      }

      @IBOutlet weak var StepCount: UILabel!



 }

Solution

  • You can fetch today's steps using HKStatisticsQuery. You can now in your view controller use getTodaysSteps method and set your label's text property.

    Swift 3.1:

        let healthStore = HKHealthStore()
    
        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
                var resultCount = 0.0
    
                guard let result = result else {
                    log.error("Failed to fetch steps = \(error?.localizedDescription ?? "N/A")")
                    completion(resultCount)
                    return
                }
    
                if let sum = result.sumQuantity() {
                    resultCount = sum.doubleValue(for: HKUnit.count())
                }
    
                DispatchQueue.main.async {
                    completion(resultCount)
                }
            }
    
            healthStore.execute(query)
        }
    

    You can call this method like this:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        getTodaysStepCount { [weak self] steps in
            self?.StepCount.text = "\(steps)"
        }
    }