iosswifthealthkithkhealthstore

How to display steps count from HealthKit Swift 3


Hi i want to display on my app dayly step count from healthKit
This is my code:

imports

import UIKit
import HealthKit

Class instance

var healthStore = HKHealthStore()

viewDidLoad method

override func viewDidLoad() {
    super.viewDidLoad()

    if HKHealthStore.isHealthDataAvailable(){
        let writeDataTypes = dataTypesToWrite()
        let readDataTypes = dataTypesToWrite()

        healthStore.requestAuthorization(toShare: writeDataTypes as? Set<HKSampleType>, read: readDataTypes as? Set<HKObjectType>, completion: { (success, error) in
            if(!success){
                print("error")

                return
            }

            self.updateSteps()

        })
    }

}

Write:

func dataTypesToWrite() -> NSSet{
    let stepsCount = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)

    let returnSet = NSSet(objects: stepsCount!)
    return returnSet
}

Read:

func dataTypesToRead() -> NSSet{
    let stepsCount = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)
    let returnSet = NSSet(objects: stepsCount!)

    return returnSet
}

Now I want to create func updateSteps()


Solution

  • I have an answer to my question

    func updateSteps(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 {
                    print("\(String(describing: error?.localizedDescription)) ")
                    completion(resultCount)
                    return
                }
    
                if let sum = result.sumQuantity() {
                    resultCount = sum.doubleValue(for: HKUnit.count())
                }
    
                DispatchQueue.main.async {
                    completion(resultCount)
                }
            }
    
            healthStore.execute(query)
        }