Does anyone know why the count of steps for a specific day would be different than what the Activity app reports? For example on the 24th the Activity reports that I walked 12,304 steps. But when I run this code it reports that I walked 12,320 steps. A 16 step difference. I would think they should be identical. Any ideas?
Thanks!
let calendar = NSCalendar.current
let startDate = calendar.startOfDay(for: Date(dateString:"2017-12-24"))
let endDate = calendar.date(byAdding: .day, value: 1, to: startDate)!
QueryHelper.distanceForDates(startDate: startDate, endDate: endDate, type: .stepCount,
unit: HKUnit.count(), completion: { (totalDistance, error) in
guard let totalDistance = totalDistance else {
guard let error = error else { return }
print("Error retrieving data: \(error)")
return
}
print("The total number of steps is: \(totalDistance)")
})
class func distanceForDates(startDate: Date, endDate: Date, type: HKQuantityTypeIdentifier, unit: HKUnit = HKUnit.count(),
completion: @escaping (Double?, Error?) -> Swift.Void) {
let healthKitStore = HKHealthStore()
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: [])
let sampleType = HKSampleType.quantityType(forIdentifier: type)!
let sampleQuery = HKStatisticsQuery(quantityType: sampleType,
quantitySamplePredicate: predicate,
options: .cumulativeSum) { query, results, error in
if results != nil {
let quantity = results?.sumQuantity()
let totalDistance = quantity?.doubleValue(for: unit)
completion(totalDistance, error)
} else {
completion(nil, error)
return
}
}
healthKitStore.execute(sampleQuery)
}