First of all add HealthKit on Capability in project singing & Capability
static func retrieveStepCount(today:Date, yesterDay: Date,completion: @escaping(Double?,Error?) -> ()) {
let inputFormatter = DateFormatter()
inputFormatter.dateFormat = "dd/MM/yyyy"
// Define the Step Quantity Type
let stepsCount = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)
// Set the Predicates & Interval
let predicate = HKQuery.predicateForSamples(withStart: today.startOfDay , end: today.endOfDay, options: .strictStartDate)
var interval = DateComponents()
interval.day = 1
//print(predicate)
let query = HKStatisticsQuery(quantityType: stepsCount!, quantitySamplePredicate: predicate, options: HKStatisticsOptions.cumulativeSum) { (query, result, error) in
var resultCount = 0.0
if error != nil {
completion(nil, error)
return
}
if let myResult = result {
if let sum = myResult.sumQuantity() {
print(sum)
resultCount = sum.doubleValue(for: HKUnit.count())
}
DispatchQueue.main.async {
completion(resultCount, nil)
}
}
}
HKHealthStore().execute(query)
}
Call above function and get steps
let startDate = Date().startOfDay
let yesterDay = Date().endOfDay
self.retrieveStepCount(today: startDate, yesterDay: yesterDay) { (steps, error) in
print(error?.localizedDescription)
if error == nil {
print("Health kit Walked steps \(steps ?? 0)")
}
}