class StepsInteractor { let healthStore = HKHealthStore() let stepCountType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)! // Access Step Count let healthKitTypes: Set = [ HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)! ] func retrieveStepsWithAuth(completion: @escaping (Double) -> Void) { // Check for Authorization if (healthStore.authorizationStatus(for: stepCountType) != HKAuthorizationStatus.sharingAuthorized) { healthStore.requestAuthorization(toShare: healthKitTypes, read: healthKitTypes) { (success, error) in if (success) { // Authorization Successful self.getSteps { (result) in completion(result) } } else { completion(-1) } } } else { self.getSteps { (result) in completion(result) } } } func getSteps(completion: @escaping (Double) -> Void) { let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!
let now = Date() let startOfDay = now - 2.days var interval = DateComponents() interval.day = 1 let query = HKStatisticsCollectionQuery( quantityType: stepsQuantityType, quantitySamplePredicate: nil, options: [.cumulativeSum], anchorDate: startOfDay, intervalComponents: interval) query.initialResultsHandler = { _, result, error in var resultCount = 0.0 result!.enumerateStatistics(from: startOfDay, to: now) { statistics, _ in if let sum = statistics.sumQuantity() { // Get steps (they are of double type) resultCount = sum.doubleValue(for: HKUnit.count()) } // end if // Return completion(resultCount) } } query.statisticsUpdateHandler = { query, statistics, statisticsCollection, error in // If new statistics are available if let sum = statistics?.sumQuantity() { let resultCount = sum.doubleValue(for: HKUnit.count()) // Return completion(resultCount) } // end if } healthStore.execute(query) } }